-1

我正在使用 choco 来解决 CSP,我的限制之一是一个变量 ( X[i][j]) 的总和小于N=10, and i=j=1....N.

我该如何做到这一点?感谢您的帮助。

sum(X[i][j]) = 1 for i=j=1....N
4

1 回答 1

0

你需要一个一维数组并调用model.sum():

import org.chocosolver.solver.Model;
import org.chocosolver.solver.Solver;
import org.chocosolver.solver.variables.BoolVar;

public class SumBooleans {

    private final static int N = 10;

    public static void main(String[] args) {
        Model model = new Model("Boolean sum");

        BoolVar[][] vars = new BoolVar[N][N];
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                vars[i][j] = model.boolVar("vars[" + i + "][" + j + "]");
            }
        }

        BoolVar[] flatArray = new BoolVar[N * N];
        for (int index = 0; index < N * N; index++) {
            int i = index / N;
            int j = index % N;
            flatArray[index] = vars[i][j];
        }

        model.sum(flatArray, "=", 1).post();
        //model.sum(flatArray, "<", N).post();
        //model.sum(flatArray, ">=", 8).post();

        Solver solver = model.getSolver();
        if (solver.solve()) {

            for (int i = 0; i < N; i++) {
                for (int j = 0; j < N; j++) {
                    System.out.print(vars[i][j].getValue() + " ");
                }
                System.out.println();
            }

        }
    }
}

输出:

0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 1 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
于 2019-01-27T11:10:48.747 回答