简体   繁体   中英

Iterate over an array in minizinc and output it

I would like to iterate over an array in MiniZinc and output the result: something like this

array[1..4] of int: my_array = [4,5,1,3];

output [forall(c in 1..4)("element index c is: \(array[c])")];

the output should be like this

element index 1 is :4
element index 1 is :5
element index 1 is :1
element index 1 is :3

is there a way to do this in MiniZinc because I would not find it in the handbook.

Thank you

array[1..4] of int: my_array = [4,5,1,3];

output [forall(c in 1..4)("element index c is: \(array[c])")];

the output should be like this

element index 1 is :4
element index 1 is :5
element index 1 is :1
element index 1 is :3

(I assume that the indices should change, ie from 1..4).

The output section requires a little different syntax. Here's one way of doing this:

array[1..4] of int: my_array = [4,5,1,3];
solve satisfy;
output [
  "element index \(c) is: \(my_array[c])\n"
  | c in 1..4
];

The output is

element index 1 is: 4
element index 2 is: 5
element index 3 is: 1
element index 4 is: 3

There is another way of doing this, outside the output section, and can be used for debugging indices and values in fixed arrays: using trace . Here's a variant that prints the same thing, but uses trace in the forall loop in the constraint section:

array[1..4] of int: my_array = [4,5,1,3];
solve satisfy;
constraint
  forall(c in 1..4) (
   trace("element index \(c) is: \(my_array[c])\n")
  )
;

Note: using trace does not print decision variables in any intelligible way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM