我有一组Choco解算器IntVar变量,比如X1,X2,...,Xn。我需要定义一个强制执行规则的约束 - 最小和最大变量之间的距离(绝对差值)值应小于固定值,比如100,即| max(X1,... Xn) - min(X1, ..,XN)| < 100。
有人可以帮忙吗?
答案 0 :(得分:0)
你有IntConstraintFactory.distance()
方法来准确地做到这一点。请参阅docs。
以下是执行您要求的实际代码:
Solver solver = new Solver();
int n = 10;
IntVar[] x = VariableFactory.boundedArray("x", n, 0, 500, solver);
IntVar min = VariableFactory.bounded("min", 0, 500, solver);
IntVar max = VariableFactory.bounded("max", 0, 500, solver);
solver.post(IntConstraintFactory.minimum(min, x));
solver.post(IntConstraintFactory.maximum(max, x));
solver.post(IntConstraintFactory.distance(min, max, "<", 100));
if (solver.findSolution()) {
int solutions = 5;
int nSol = 0;
do {
System.out.print("x: ");
for (int i = 0; i < n; i++)
System.out.print(x[i].getValue() + " ");
System.out.println("\nmin = " + min.getValue() + ", max = " + max.getValue() + ", |min - max| = " + Math.abs(min.getValue() - max.getValue()) + "\n");
nSol++;
if (solutions > 0 && nSol >= solutions)
break;
} while (solver.nextSolution());
System.out.println(nSol + " solutions found.");
} else {
System.out.println("No solution found.");
}