Skip to content

Constrain Every Array Element

Problem

Every element of a random array must satisfy the same constraint, and writing one constraint per index does not scale with the array size.

Solution

Use a foreach constraint with an index_identifier. The constraint body is applied to each element in turn.

1
2
3
4
5
6
7
8
9
rand array<bit [4], 4> nibbleArray;
constraint {
    nibbleArray[0] in [2..3];
    nibbleArray[1] in [2..3];
    nibbleArray[2] in [2..3];
    nibbleArray[3] in [2..3];
}
...
//  do something with solved nibbleArray
1
2
3
4
5
6
rand array<bit [4], 4> nibbleArray;
constraint {
    foreach(nibbleArray[i]) nibbleArray[i] in [2..3];   // (1)!
}
...
//  do something with solved nibbleArray
  1. Note that using the iterator_identifier format (e.g., foreach(i : nibbleArray)) cannot constrain the array's elements.

See also