Minizinc嵌套for循环

时间:2016-01-29 19:17:34

标签: minizinc

我如何在Minizinc中使用嵌套for循环(就像下面的java所做的那样)来生成/填充数组?

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 个答案:

答案 0 :(得分:5)

有两种方法可以执行此操作,具体取决于diff矩阵的性质(下面称为diffs,因为diff是保留字)。

两种方法都使用相同的启动和输出。

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)作为决策变量。    如果diffs是决策变量矩阵,那么您可以这样做:

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)作为常数矩阵    如果diffs矩阵只是一个常量矩阵,那么你可以直接初始化它:

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
   % ... 
;

我假设模型包含的约束和决策变量多于此,因此我建议您使用第二种(&#34;常量&#34;)方法,因为解算器更容易解决。