choco

sum one variable (X[i][j]) in one constraint with choco


I am using choco to solve a CSP , and one of my constraints is that the sum of one variables (X[i][j]) is less than N=10, and i=j=1....N.

How do I accomplish this? thank you for your help.

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

Solution

  • You need a 1d array and call 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();
                }
    
            }
        }
    }
    

    Output:

    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