Shuffle a list in Minizinc

320 Views Asked by At
array[1..6] of var 0..1: Path;
include "alldifferent.mzn";
constraint
forall(j in 1..6)(
alldifferent(i in 1..6)(Path[i])
)

Iam trying to shuffle a list into minizinc but i want different results every time like with a for all . how can i do it? print this:

Path = array1d(1..6, [5, 4, 3, 2, 1, 0]);
1

There are 1 best solutions below

2
On

There are - at least - two approaches for generating a random matrix depending on if you want to generate all possible variables (the first model below using decision values), or if you just want a "random" random matrix (the second model using built-in random generator). (A third approach would be that you write your own random generator, but this is left as an exercise :-)).

Here is a simple MiniZinc model that generates all the possible 6x6 matrices of {0,1} as decision variables.

int: n = 6;
array[1..n,1..n] of var 0..1: x;
solve :: int_search(array1d(x), first_fail, indomain_random) satisfy;

constraint
  true
;

output
[
   if j = 1 then "\n" else " " endif ++
      show(x[i,j])
   | i,j in 1..n        
];

Note: The indomain_random heuristic generates the solutions in a more "random-like" order.

There is another way of doing this, using the bernoulli(0.5) function, which generates randomly 0 or 1 during the creation of the model, i.e. it's not decision variables:

int: n = 6;
array[1..n,1..n] of int: x = array2d(1..n,1..n,[ bernoulli(0.5) | i,j in 1..n]);

solve satisfy;

constraint
  true
;

output
[
  if j = 1 then "\n" else " " endif ++
    show(x[i,j])
  | i,j in 1..n        
];

Which happens to generate the following matrix:

1 1 1 0 0 0
1 0 1 1 0 0
0 0 0 0 1 1
0 1 0 0 1 0
1 1 1 1 0 1
0 1 1 1 1 1

The drawback of this is that you then have to manually seed the random generator for generating different matrices. This is (according to https://www.minizinc.org/doc-2.5.1/en/command_line.html?highlight=random#cmdoption-r ) done with the --random-seed i flag (or -r i) but this don't work right now on my MiniZinc version.

MiniZinc has quite a few random generators, see more here: https://www.minizinc.org/doc-2.5.1/en/lib-stdlib.html?highlight=random#random-number-generator-builtins .