yet another knapsack question... I understand the concept of the knapsack problem but I am having troubles with parts of my code.. I would like to believe that I am headed into the right direction but maybe not?
Let's say I have a list of 1,2,3,6,7 and my goal weight is 4:
The items that will equal this weight are 1 and 3.
My first iteration will go like this:
Item: 1
Goal Weight: 3 (I did weight - the item)
Items: 1,2
Goal Weight: 1
Items: 1,2,3
Goal Weight: -2
-- Once the weight reaches < 0, it should restart the goal weight and then restart the position
but the items should start at 1 and skip over 2, going straight to 3. An Example below:
Items: 1
Goal Weight: 3
Items: 1, 3
Goal Weight: 0 // Finished
--However, I do not know how skip over the 2 and go to 3. In a way, I understand that this problem uses combinations/permutations. I just can't get my code to work the way I want it to. Below is my code. Please let me know if I am unclear in anything.
public boolean recursive(int weight, int start){
if(weight == 0){// if weight is zero, we found what we wanted.
System.out.println("We did it");
return true;
}
else if(weight < 0){ //Too much weight in the bag.
if(start == storeItems.length-1){ //reached the end of the array.
recursive(goalWeight, start + 1);
return false;
}
else{ // did not reach end of the array but still not the right combination of numbers.
recursive(weight, start + 1);
}
}
else if(weight > 0){
System.out.println(storeItems[start]);
boolean x = recursive(weight - storeItems[start], start + 1);
}else{
System.out.print("No values");
}
return false;
}