Search code examples
minizinc

Minizinc nested for loop


How could I use nested for loop(like what java does below) to generate/populate arrays in Minizinc?

int[][] input1 = {{1,1,1}, {3,3,3}, {5,5,5} };
int[][] input2 = {{2,6,9},{7,7,7}, {9,9,9}, {11,11,11} };
int[][] diff = new int[input1.length][input2.length];
for(int i = 0; i < input1.length; i++){
    for(int j = 0; j < input2.length; j++){
        for(int k = 0; k < 3; k++){
            diff[i][j] += input1[i][k]-input2[j][k]; 
        }
    }
}

Solution

  • There are two approaches doing this, depending on the nature of the diff matrix (which is called diffs below since diff is a reserved word).

    Both approaches use the same initiation and output.

    int: n = 3;
    int: m = 4;
    
    array[1..n,1..n] of int: input1 = array2d(1..n,1..n,[1,1,1, 3,3,3, 5,5,5 ]);
    array[1..m,1..n] of int: input2 = array2d(1..4,1..n,[2,6,9, 7,7,7, 9,9,9, 11,11,11 ]);
    
    output [
       if k = 1 then "\n" else " " endif ++
          show(diffs[i,k])
       | i in 1..n, k in 1..m
    ];
    

    1) As decision variables. If diffs is a matrix of decision variables, then you can do like this:

    array[1..n,1..m] of var int: diffs;
    
    constraint 
       forall(i in 1..n, j in 1..m) (
         diffs[i,j] = sum(k in 1..n) ( input1[i,k]-input2[j,k] )
       )
    ;
    

    2) As a constant matrix If the diffs matrix is just a matrix of constants then you can initialize it directly:

    array[1..n,1..m] of int: diffs = array2d(1..n,1..m, [sum(k in 1..n) (input1[i,k]-input2[j,k]) | i in 1..n, j in 1..m]);
    
    constraint
       % ... 
    ;
    

    I assume that the model contains more constraints and decision variables than this, so I suggest that you work with the second ("constant") approach since it will be easier for the solvers to solve.