简体   繁体   English

使用Choco Solver在背包中分配物品

[英]Item allocation in a knapsack with Choco Solver

I try to implement a multidimensionnal knapsack problem with Choco Solver through JAVA. 我尝试通过JAVA使用Choco Solver实现多维背包问题。 My idea is to assign 3 items in 2 knapsacks. 我的想法是在2个背包中分配3个物品。

My item have a weight and knapsack a limit : int[] itemWeight = {2, 2, 2}; 我的商品有重量,背包有限制:int [] itemWeight = {2,2,2}; int[] knapsackLimit = {4, 4}; int [] knapsackLimit = {4,4};

And my decision variable where 3 items have a knapsack between {0, 1} : int[] itemAllocation = {1, 1, 0}; 还有我的决策变量,其中3个项目在{0,1}之间有背包:int [] itemAllocation = {1,1,0};

I wrote this problem by using Choco Solver : 我通过使用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] 我总是得到以下分配:[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). 请注意,发布不是自动的,因为您可能想验证约束而不是发布约束(例如发生在ifThen语句中)。

Best, 最好,

https://www.cosling.com/ https://www.cosling.com/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM