问题
I'm looking for a solution to the knapsack problem where multiple constraints are in place.
Say our knapsack has a maximum weight of 30kg and we have a set of 100 objects, each with a weight and each with a benefit. These objects could look like this:
{ name: 'water bottle', weight: 2, benefit: 5 },
{ name: 'potatoes', weight: 10, benefit: 6 }
Finding the combination of objects with the highest benefit within the maximum weight is simple enough. Here is a nodeJS plugin showing how it can be done... https://gist.github.com/danwoods/7496329
Where I'm struggling is when the objects have more properties and the knapsack has more limitations.
Constraints: Max weight of 30, Use exactly 8 objects, Use a maximum of 3 of any object 'type', Use a maximum of 3 of any object 'colour'
{ name: 'water bottle', weight: 2, benefit: 5, type: 'drink', colour: 'clear' },
{ name: 'potatoes', weight: 10, benefit: 6, type: 'food', colour: 'beige' }
How can the optimal combination of objects be found with these extra rules in place?
Can the knapsack solver linked to above be modified or is a new approach needed?
回答1:
Maybe this won't help your code, but it can help to modeling your problem. lets say decision variable is x[i] = binary.
max capacity:
sum{i in Object} weight[i]*x[i] <=capacity;
use exactly 8 objects:
sum{i in Object} x[i] = 8;
use max 3 object type:
sum{i in object} type[i]*x[i] <=3;
use max 3 object color:
sum{i in Object} color[i]*x[i] <=3;
来源:https://stackoverflow.com/questions/41923706/optimisation-knapsack-algorithm-with-multiple-contraints-in-javascript