I try to implement a multidimensionnal knapsack problem with Choco Solver through JAVA. My idea is to assign 3 items in 2 knapsacks.
My item have a weight and knapsack a limit : int[] itemWeight = {2, 2, 2}; int[] knapsackLimit = {4, 4};
And my decision variable where 3 items have a knapsack between {0, 1} : int[] itemAllocation = {1, 1, 0};
I wrote this problem by using Choco Solver :
Model model = new Model("KnapsackProblem");
// Allocation variable
IntVar[] x = new IntVar[3];
for (int i = 0; i < itemNumber; i++) {
x[i] = model.intVar("x"+i, 0, knapsackNumber-1);
}
// Knapsack capacities variables
IntVar[] limitVar = new IntVar[knapsackNumber];
for (int i = 0; i < knapsackNumber; i++) {
limit[i] = model.intVar(knapsackLimit[i]);
}
IntVar[] itemWeightVar = new IntVar[itemNumber];
for (int i = 0; i < itemNumber; i++) {
itemWeightVar[i] = model.intVar(0, 2);
model.element(itemWeightVar[i], itemWeight,x[i]);
}
// Limit Cosntraints
for (int i = 0; i < knapsackNumber; i++) {
model.sum(itemWeightVar, "<=", limit[x[i].getValue()]);
}
model.getSolver().solve();
Unfortunately, this method does not work. I always get the following allocation: [x0 = 0, x1 = 0, x2 = 0]
Thank you in advance.
This is a common mistake, you simply forget to POST your constraints so they are not taken into account. For instance, you should replace
model.element(itemWeightVar[i], itemWeight,x[i]);
by
model.element(itemWeightVar[i], itemWeight,x[i]).post();
Note that the post is not automatic as you may want to reify the constraint instead of posting it (which happens within ifThen statements for instance).
Best,
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.