Skip to content

Unique Random Values with shuffle()

Problem

Several variables must take pairwise-distinct random values. A unique constraint expresses this directly, but as the number of variables grows the solver may fail to find a solution within its iteration limit.

Solution

Fill a list with every candidate value, shuffle() it, and take the values from the front of the list. Each value is used at most once, so the results are distinct without any solver work.

1
2
3
4
5
6
rand array<bit [4], 4> nibbleArray;
constraint {
    unique {nibbleArray[0], nibbleArray[1], nibbleArray[2], nibbleArray[3]};
}
...
//  do something with solved nibbleArray
1
2
3
4
5
6
7
8
9
array<bit [4], 4> nibbleArray;
list <bit [4]   > element_pool;
exec pre_solve {
    repeat (i : 16) element_pool.push_back(i);  //  element_pool: {} -> {0..15}
    element_pool.shuffle();
    foreach(nibbleArray[i]) nibbleArray[i] = element_pool.pop_front();
}
...
//  do something with solved nibbleArray

See also