Minizinc nested for loop

梦想的初衷 提交于 2019-12-11 01:39:35

问题


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]; 
        }
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/35092341/minizinc-nested-for-loop

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