我找到了用 choco 求解器求解幻方程序的代码:
public static void main(String[] args) {
int n = 4;
System.out.println("Magic Square Problem with n = " + n);
Problem myPb = new Problem();
IntVar[] vars = new IntVar[n * n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
vars[i * n + j] = myPb.makeEnumIntVar("C" + i + "_" + j, 1, n * n);
}
IntVar sum = myPb.makeEnumIntVar("S", 1, n * n * (n * n + 1) / 2);
myPb.post(myPb.eq(sum, n * (n*n + 1) / 2));
for (int i = 0; i < n * n; i++)
for (int j = 0; j < i; j++)
myPb.post(myPb.neq(vars[i], vars[j]));
int[] coeffs = new int[n];
for (int i = 0; i < n; i++) {
coeffs[i] = 1;
}
for (int i = 0; i < n; i++) {
IntVar[] col = new IntVar[n];
IntVar[] row = new IntVar[n];
for (int j = 0; j < n; j++) {
col[j] = vars[i * n + j];
row[j] = vars[j * n + i];
}
myPb.post(myPb.eq(myPb.scalar(coeffs, row), sum));
myPb.post(myPb.eq(myPb.scalar(coeffs, col), sum));
myPb.solve();
}
但是“问题”类似乎已被“模型”类取代。使用 Model.intVar 而不是 Problem.makeEnumIntVar 是否正确?替换 Problem.neq、Problem.eq 和 Problem.scalar 的当前函数是什么?