JaCoP: Solving an 0/1 knapsack problem
I've been trying to teach myself how to use the JaCoP constraint programming library but I'm having a bit of difficulty implementing an 0/1 knapsack problem. I've tried a problem size of 4 and defined the items and variables as follows:
knapsack[0] = new KnapsackItem(quantity[0], 5, 7);
knapsack[1] = new KnapsackItem(quantity[1], 7, 9);
knapsack[2] = new KnapsackItem(quantity[2], 2, 3);
knapsack[3] = new KnapsackItem(quantity[3], 3, 3);
IntVar knapsackCapacity = new IntVar(store, "capacity", 0, 10);
IntVar knapsackProfit = new IntVar(store, "profit", 0, 22);
I've then added a Knapsack constraint using the knapsack list:
Constraint con = new Knapsack(knapsack, knapsackCapacity, knapsackProfit); store.impose(con);
And I have then searched for a solution in the way given in the tutorial:
//search for a solution and print results
Search<IntVar> search = new DepthFirstSearch<IntVar>();
SelectChoicePoint<IntVar> select = new Input开发者_如何学COrderSelect<IntVar>(store, quantity,
new IndomainMin<IntVar>());
boolean result = search.labeling(store, select);
if (result) {
System.out.println("Solution: "+quantity[0]+", "+quantity[1]+", "+quantity[2]+", "+quantity[3]);
} else {
System.out.println("*** No");
}
The result I get is simply that all the quantities are zero, which satisfies the constraints but doesn't optimise anything. Is there another constraint or something I should add to try and maximise profit * quantity for each item?
Thank you
Ben
I have not used the Knapsack
constraint, but in general to optimize (minimize) you use the following (the cost as third argument):
search.labeling(store, select, cost);
Note that this minimizes the cost, so you must convert the profit to a "negative cost". The example ExamplesJaCoP/KnapsackExample.java
(combined with ExamplesJaCoP/Example.java
) show the principle. However, the example don't useKnapsackItem
, just plain IntVar
.
精彩评论