gpt4 book ai didi

Minizinc 嵌套 for 循环

转载 作者:行者123 更新时间:2023-12-03 22:16:03 31 4
gpt4 key购买 nike

我如何使用嵌套 for 循环(就像下面 java 所做的那样)在 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];
}
}
}

最佳答案

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

我假设模型包含比这更多的约束和决策变量,所以我建议您使用第二种(“常量”)方法,因为它更容易求解。

关于Minizinc 嵌套 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35092341/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com