Minizinc嵌套循环 [英] Minizinc nested for loop

查看:101
本文介绍了Minizinc嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用嵌套的for循环(如下面的Java那样)在Minizinc中生成/填充数组?

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

推荐答案

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

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

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)作为常数矩阵 如果diffs矩阵只是常量矩阵,则可以直接对其进行初始化:

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.

这篇关于Minizinc嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆