Generate unique elements without unique

HI All,

I went through paper “The Top Most Common SystemVerilog Constrained Random Gotchas”, (page 24) found the following code for unique numbers;


module p1;
class dummy_c;
	randc bit [31:0] val;
endclass

class trans;
	rand bit [31:0] addrs [];
  
	function void post_randomize();
	dummy_c dc = new;
	foreach (addrs[i]) begin
	assert (dc.randomize);
	addrs[i] = dc.val;
	end
    $display("unique elements %0p",dc);
	endfunction
  
endclass
  trans obj;
  initial begin
    obj = new;
    repeat (6)
    obj.randomize();
  end
endmodule

When I display the value, I am getting zero values.
Could you please help me in completing the code to get the unique random numbers?

Thank You,

Set the size of the dynamic array. For example, I set it to 4:


module p1;
    class dummy_c;
        randc bit [31:0] val;
    endclass
 
    class trans;
        rand bit [31:0] addrs [] = new[4];
        function void post_randomize();
            dummy_c dc = new;
            foreach (addrs[i]) begin
                assert (dc.randomize);
                addrs[i] = dc.val;
            end
            $display("unique elements %p", addrs);
        endfunction
    endclass

    trans obj;
    initial begin
        obj = new;
        repeat (6) obj.randomize();
    end
endmodule

Output:


unique elements '{'h1ff7584c, 'hd57c8fba, 'h4912c3a3, 'h303f2b73}
unique elements '{'h2bee66cd, 'h54105e58, 'h6ed1ae0a, 'h8992fdbc}
unique elements '{'h54bcb62b, 'h82dcfd44, 'hb0fd445d, 'h3b5e19aa}
unique elements '{'hc6ec4b9f, 'h3ffebac0, 'ha92a8e4c, 'h125661da}
unique elements '{'hab91aa56, 'hb02cf771, 'hbdfedec2, 'hc73578f8}
unique elements '{'hf3c96e0, 'h307b9421, 'hf7f583a7, 'h72f98ea3}