Minizinc 嵌套 for 循环
Minizinc nested for loop
如何在 Minizinc 中对 generate/populate 数组使用嵌套 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];
}
}
}
根据 diff
矩阵(由于 diff
是保留字,下面称为 diffs
)的性质,有两种方法可以做到这一点。
两种方法使用相同的启动和输出。
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
% ...
;
我假设模型包含的约束和决策变量比这更多,所以我建议您使用第二种 ("constant") 方法,因为它更容易求解。
如何在 Minizinc 中对 generate/populate 数组使用嵌套 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];
}
}
}
根据 diff
矩阵(由于 diff
是保留字,下面称为 diffs
)的性质,有两种方法可以做到这一点。
两种方法使用相同的启动和输出。
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
% ...
;
我假设模型包含的约束和决策变量比这更多,所以我建议您使用第二种 ("constant") 方法,因为它更容易求解。