[英]Is there a way to swap columns of a 2d array (matrix) in MiniZinc, and keep track of that?
我目前正在研究 MiniZinc。
我得到了以下二維數組(矩陣):
0 1 0 0 0 0
0 1 1 1 0 1
0 0 0 0 1 1
假設它有一些順序。 左邊的第一列是第一列,右邊的下一列是第二列,依此類推,例如:
1 2 3 4 5 6
----------------
0 1 0 0 0 0
0 1 1 1 0 1
0 0 0 0 1 1
我需要一種方法(比如約束或其他東西)來幫助我減少一行中的第一個 1 和同一行的最后一個 1 之間的距離。 例如,一個理想的矩陣是:
1 2 3 4 6 5
----------------
0 1 0 0 0 0
0 1 1 1 1 0
0 0 0 0 1 1
如您所見,這是通過將第 5 列和第 6 列交換在一起。 但我不知道如何做到這一點,並跟蹤順序,知道第一個矩陣有 [1 2 3 4 5 6] 而第二個是 [1 2 3 4 6 5]
我真的不知道如何 model 那種交換二維變量數組中的列。
謝謝您的幫助!
這是一個簡單的方法:假設您的原始數據矩陣是data
。 您可以使用數組(例如x
)來跟蹤列的新順序。 要使用新訂單,請使用data[row,x[col]]
,例如
[data[row,x[col]] | row in 1..num_rows, col in 1..num_cols]
這是一個小例子。 請注意,您必須在x
上添加約束以使其更有趣。
include "globals.mzn";
int: num_rows;
int: num_cols;
array[1..num_rows, 1..num_cols] of int: data;
% decision variables
array[1..num_cols] of var 1..num_cols: x;
solve satisfy;
constraint
all_different(x)
% /\ more constraints on x ....
;
output [
"data:\n",
show2d(data) ++ "\n" ++
"x: \(x)\n",
"new_data:\n",
show2d(array2d(1..num_rows, 1..num_cols, [data[i,x[j]] | i in 1..num_rows,j in 1..num_cols])) ++ "\n"
];
% data
num_rows = 3;
num_cols = 6;
data = array2d(1..num_rows,1..num_cols,
[
0,1,0,0,0,0,
0,1,1,1,0,1,
0,0,0,0,1,1
]);
解決方案之一是:
data:
[| 0, 1, 0, 0, 0, 0 |
0, 1, 1, 1, 0, 1 |
0, 0, 0, 0, 1, 1 |]
x: [3, 1, 4, 5, 2, 6]
new_data:
[| 0, 0, 0, 0, 1, 0 |
1, 0, 1, 0, 1, 1 |
0, 0, 0, 1, 0, 1 |]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.