我正在寻找一种在 Choco Solver 上编码数学方程的方法。 我发现有一种方法可以对约束进行编码,例如:
x + y < 9
但是我正在尝试编码类似的东西
3x + 4y < 9
其中 x 和 y 是 int 变量。
任何帮助将不胜感激。
最佳答案
我也是 Choco 新手,但我可以解决这个问题。
为此,您可以使用约束标量
(请参阅 docs )。
首先,您只需在两个 IntVar
变量中定义 x
和 y
即可。您可以使用 VariableFactory.bounded
或 Variable.enumerated
。当您只想使用具有下界和上限的域时,它们非常相似,但差异在user guide中进行了解释。 .
然后您需要定义一个包含方程系数的数组,在本例中为 { 3, 4 }
。
具体操作方法如下:
Solver solver = new Solver();
IntVar x = VariableFactory.bounded("x", 0, 50, solver);
IntVar y = VariableFactory.bounded("y", 0, 50, solver);
int[] coefficients = new int[]{ 3, 4 };
solver.post(IntConstraintFactory.scalar(new IntVar[]{ x, y }, coefficients, "<", VariableFactory.fixed(9, solver)));
if (solver.findSolution()) {
do {
System.out.println("x = " + x.getValue() + ", y = " + y.getValue());
} while (solver.nextSolution());
} else {
System.out.println("The equation has no solutions.");
}
关于java - 使用 choco 求解器求解方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35688831/