Skip to content

Constrain the Sum of an Array

Problem

The elements of a random array are free individually, but their total must equal a given value (for example, a set of sizes that must add up to a buffer length).

Solution

Call sum() on the array inside a constraint block. The solver treats it as a constraint over all elements, so other per-element constraints can be combined with it.

1
2
3
4
5
6
rand array<int, 2> intArray;

constraint {
    intArray.sum() == 3;
    intArray[0] == 2;   //  intArray: {0, 0} -> {2, 1}
}

Note

sum() applies to arrays whose element type is an integer type (bit or int). The same constraint works on a square-form declaration (rand int intArray [2];).

See also