Consider a list of weights and a list of bags with variable weights. I need an algorithm that finds the minimum number of bags needed to store all weights.
Simply sorting in decreasing order doesn't work. Consider this example:
weights = [8,7,4,4]
bags = [16,7,5,5]
If we start inserting the weights in decreasing order, we end up with:
1st bag (capacity of 16): [8,7]
2nd bag (capacity of 7): [4]
3rd bag (capacity of 5): [4]
Whereas the optimal solution is:
1st bag: [8,4,4]
2nd bag: [7]
This problem can be considered as a variant of the Bin packing problem.
The problem is NP-hard, and various (exponential-time) exact algorithms have already been proposed for it (here). One simple way to solve the problem instance you described (in an exact manner) is to model it as an integer linear program:
The first four constraints indicate that each item has to be placed in exactly one bin, and the second four constraints are in fact capacity constraints. As you can see, the variables
y[1], y[2], y[3], y[4]are all boolean. The variabley[i]indicates that whether or not the i-th bin is employed. I solved the model by the Gecode solver in MiniZinc. One optimal solution is:The solution says that we have to place the the item of weight 8, the items of weight 4 in the first bin, and the item of weight 7 in the second bin.