I have a dynamic array(dyn) of size set to 10 which should be randomized such that 3 elements adds up to 15. I achieved it using a temporary array(temp) as shown below but I am sure there is a better way of achieving this.
Any thoughts of any alternative approach?
I also noticed that if I change the “bit[3:0]” to “int”, simulation hangs.
How can we achieve similar result i.e 3 entries add up to 15 if dyn is a 2 dimensional array?
In reply to rikb2014:
I can’t think of a way of doing this without a temporary helper array. It might be simpler to have an array of bits that select which array elements to sum.
And remember the sum() method always returns a results with the same type as the array’s elements. You have to worry about overflow. See SV contraint to repeat elements n time - SystemVerilog - Verification Academy.
module top;
class pkt;
rand bit [3:0] dyn[][];
rand bit tmp[][];
constraint dyn_c {
// 2d array 5X6
dyn.size == 5; foreach (dyn[i]) dyn[i].size == 6;
// dyn and tmp arrays have the same size
dyn.size == tmp.size; foreach (dyn[i]) dyn[i].size == tmp[i].size;
// turn on only three elements in tmp array
tmp.sum(tmp_i) with (tmp_i.sum(tmp_ij) with (int'(tmp_ij))) == 3;
// sum of selected elements musted be 15
dyn.sum(dyn_i) with (dyn_i.sum(dyn_ij) with (int'(dyn_ij*tmp[dyn_i.index][dyn_ij.index]))) == 15;
}
endclass : pkt
pkt p =new;
initial repeat (5) begin
assert(p.randomize());
$display("%p",p);
end
endmodule