Choco solver old class

瘦欲@ 提交于 2019-12-11 15:07:05

问题


I found this code for solving the magic square program with the choco solver:

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();
}    

But the class 'Problem' seems to have been replaced with the 'Model' class. Is it correct to use Model.intVar instead of Problem.makeEnumIntVar? What would be the current function that replaces Problem.neq, Problem.eq and Problem.scalar?


回答1:


It looks like you have some deprecated code there. The expressions

Problem.scalar and Problem.eq

can be expressed as

int capacity = 34;  // max capacity
int[] volumes = new int[]{7, 5, 3};

 // Problem.scalar
model.scalar(new IntVar[]{obj1, obj2, obj3}, volumes, "=", capacity).post();

// Problem.eq   
model.arithm(obj1, "=", obj2).post(); 

The above code for example expresses the constraint that the scalar product is equal to capacity and that obj1 must be equal to obj2.

Further reading and resources:

Here you will find the latests tutorial with some sample code: choco tutorial

Finally you can also check out the Testcases at github:https://github.com/chocoteam/choco-solver/tree/master/src/test/java/org/chocosolver/solver

Especially the tests for variables and expression might be interesting for you.

Some more code examples can be found here: more code samples



来源:https://stackoverflow.com/questions/47533057/choco-solver-old-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!