For example I have numbers 164, 211, 225, 258, 266, 313. And I have array with 61, 55, 55, 55, 55, 47, 47, 47, 47, 69, 69, 120, 28, 91. I want to check if by adding a combination of the numbers from the second array I can possibly get one of the numbers from the first array and if so, which of the numbers I need to add. How do I do this? Note that a number in the array can only be used once.
My head is about to explode from to implement this. My basic idea is to first add all combinations of any 2 integers in the array, then add all combinations of any 3 integers in the array, etc until you add all of the numbers in the array.
Of course there is a more efficient way of doing this but this seems the simplest to me.
PS: I am also not sure about whether I can overwrite an array with a new array with new size each time thru a loop. But it doesn't give me an error.
This is as far as I got so far. When I got to the identical 2 loops one inside each other I realized I am doing something wrong and it can all be done with 1 big loop. But I mean the deepness of loops in this case depends on how many ints we are currently adding so how would that work?
/*Simply compares the integer to see if it equals to one of the desired results*/
public static boolean desiredResult(int input)
{
boolean desiredResult = false;
if (input == 164 || input == 211 || input == 225 || input == 258 || input == 266 || input == 313)
{
desiredResult = true;
}
return desiredResult;
}
public static void main(String[] args)
{
int[] additions = {61, 55, 55, 55, 55, 47, 47, 47, 47, 69, 69, 120, 28, 91}; //the array of numbers to be added
int[] currentAdd; //the numbers that are currently being added
int currentAddIndex; //the index of the array of numbers that are being added currently
for (int howManyIntsAdded=2; howManyIntsAdded<additions.length; howManyIntsAdded++) //how many integers to be added together 2-13
{
currentAdd = new int[howManyIntsAdded]; //array of numbers currently being added depending on howManyIntsAdded
for (int firstIndex=0; firstIndex<additions.length-(howManyIntsAdded-1); firstIndex++) //determine the first number to add
{
currentAddIndex = 0;
currentAdd[currentAddIndex] = additions[firstIndex];
currentAddIndex++;
for (int secondIndex=firstIndex+1; secondIndex<additions.length-(howManyIntsAdded-2); secondIndex++) //second number to add
{
currentAdd[currentAddIndex] = additions[secondIndex];
currentAddIndex++;
}
}
}
}
Any help would be extremely appreciated. I am totally lost here.


Sign In
Create Account


Back to top









