用choco在一个约束中求和一个变量(X [i] [j])

时间:2019-01-25 13:04:18

标签: choco

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

我该如何完成?谢谢您的帮助。

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

1 个答案:

答案 0 :(得分:0)

您需要一个1d数组并调用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