VLSI DV Interview Puzzles · All levels
foreach Inline Constraint on Dynamic Array
Does this randomize call have one solution or many? State the exact resulting n and data.
Puzzle
Difficulty: Medium · Puzzle 3 of 6 · Topic: randomize() with Puzzles
Does this randomize call have one solution or many? State the exact resulting n and data.
Code
systemverilog
class payload_req;
rand int unsigned n;
rand byte data[];
constraint c_base {
n inside {[2:4]};
data.size() == n;
}
endclass
payload_req r = new();
assert(r.randomize() with {
n == 3;
foreach (data[i]) data[i] == i;
});Hint
n fixes size first; foreach fixes each element exactly.
Step-by-step solution
diagram
1) Inline constraint fixes n=3.
2) data.size()==n gives size 3.
3) foreach imposes data[0]=0, data[1]=1, data[2]=2.
4) Exactly one legal assignment exists.Answer
Answer: Deterministic outcome: n=3 and data='{0,1,2}; success probability is effectively 100% because the set is satisfiable and unique.
Why candidates get it wrong
Some assume foreach introduces randomness by itself; equality in foreach can make the result fully deterministic.
Interviewer follow-up
How would you tweak foreach to keep n=3 but allow 8 distinct data combinations?