Difficulty: Medium · Puzzle 3 of 6 · Topic: randomize() with Puzzles
How many solutions does the class have, and what is P(a[0]==2)? Then: how many solutions if the foreach bound becomes a[i] < 3, and how many if an ascending-order constraint a[0]<a[1]<a[2]<a[3] is added to the original?
class uq;
rand bit [3:0] a[4];
constraint c_rng { foreach (a[i]) a[i] < 5; }
constraint c_uq { unique { a }; }
endclassEach element comes from 0..4; unique means all four elements differ.
1) Each of the 4 elements is in 0..4 (5 values) and all must differ: 5 x 4 x 3 x 2 = 120 ordered selections (5P4).
2) a[0]==2: choose the other three from the remaining four values: 4 x 3 x 2 = 24, so P(a[0]==2)=24/120=1/5 (by symmetry every value is 1/5).
3) With a[i] < 3: only 3 values for 4 distinct slots, so there is no solution and randomize() returns 0.
4) With ascending order added to the original: a strictly increasing 4-subset of {0..4} is one subset per choice of the omitted value, so C(5,4)=5 solutions; P(a[0]==0)=4/5.Answer: 120 solutions, P(a[0]==2)=1/5; a[i]<3 is unsatisfiable (randomize fails); with ascending order only 5 solutions remain.
Checked by running a model of the rule in a Python model and Verilator 5. Exact enumeration of the constraint set per the LRM (the LRM defines the distribution; simulator solvers need not be uniform). Enumerates the 4-element arrays over the allowed values with all elements distinct (pigeonhole when fewer than 4 values exist). Verilator 5.048: the unique array always solves with four distinct values from 0..4, the ascending variant solves and is ascending, and a[i]<3 returns 0.
unique is a pigeonhole constraint: four distinct values need at least four available values. Narrowing the element range to 0..2 does not make fewer solutions, it makes zero (and randomize() returns 0). Verified on Verilator 5.048: the original, a[0]==2 and ascending versions all solved (ascending gave 1 2 3 4) and the a[i]<3 variant failed; counts themselves are exact enumeration.
With a[i] < 4 instead of < 5, how many solutions are there and what is P(a[0]==0)? Model answer: four distinct values from {0,1,2,3} fill four slots, so the array is a permutation: 4! = 24 solutions and P(a[0]==0)=6/24=1/4.
Four unique elements from five values, zero to four, gives five times four times three times two, which is 120 solutions, and by symmetry the probability that a[0] is two is one fifth. If the bound becomes less than three there are only three values for four distinct slots, so there is no solution and randomize returns zero. With ascending order added, there are only five solutions, one for each omitted value. The trap is thinking a narrower range gives fewer solutions; unique is a pigeonhole constraint, so it gives none. Next I would check the range is at least as large as the array.