Суммируйте одну переменную (X [i] [j]) в одном ограничении с помощью choco - PullRequest
0 голосов
/ 25 января 2019

Я использую choco для решения CSP, и одно из моих ограничений заключается в том, что сумма одной переменной (X[i][j]) меньше N=10, and i=j=1....N.

Как мне это сделать? спасибо за вашу помощь.

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

1 Ответ

0 голосов
/ 27 января 2019

Вам нужен 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 
...