Bounded Knapsack Problem set-up. Want: a list of all possible packings
-
28-09-2019 - |
Question
Rather than optimize anything, I want to list all the possible - including "incomplete" - packings of the knapsack. Of course, I could loop through all subsets of the set of objects and pick the ones satisfying the weight constraint (can be improved by placing an upper bound on the size of the subsets to look through), but I'd really like something more efficient.
Thanks.
Solution
First sort your objects by weight. Then recursively pack the knapsack. If the smallest weight object not yet considered does not fit, or we have no objects remaining, then add the current knapsack to our list and return, else add the current knapsack to our list for each object in the list that fits put it in and try to pack the rest of the knapsack with objects heavier than the last object we packed.
If we can pack more than one item of a given type then replace less than with less than or equal to.
If we have multiple objects of the same weight we need to sort first by weight, then by some arbitrary order, and use that.
PackKnapsack(knapsack, objects)
add knapsack to list
if objects is empty return
if smallest object does not fit return
for each object in order from smallest to largest
if currentobject does not fit
break
PackKnapsack(knapsack + currentObject, objects heavier than current object)