Randomize Associative Array
Table of Contents
As associative array stores entries in the sparse matrix, there is no meaning of randomizing array size. It is good to have randomization only for associative array elements.
There are no many use cases in randomizing associative array. Only to look array operations below example’s shows the possibility to randomize associative array size and elements.
randomize associative array size
In below example, associative array size will get randomized based on size constraint, and array elements will get random values
- Declare array with rand
- On randomization, the array will get random values
class assoc_array; rand bit [7:0] array[*]; constraint size_c { array.size() inside {[4:10]}; } function void display(); $display("array size is = %0d",array.size()); $display("array = %p",array); endfunction endclass program assoc_array_randomization; assoc_array pkt; initial begin pkt = new(); pkt.randomize(); pkt.display(); end endprogram
Simulator Output
array size is = 7 array = '{0x0:'h88, 0x1:'h9b, 0x2:'h9a, 0x3:'h10, 0x4:'h5f, 0x5:'hde, 0x6:'h84}
Generate random values in an array
Below example shows the associative array with the element type enum.
typedef enum {RED,GREEN,YELLOW} color_t; class assoc_array; rand bit [7:0] colors[color_t]; constraint colors_c { foreach(colors[ii]) colors[ii] > 4; } constraint colors_s { colors.num() == 3; } function void display(); $display("colors array size is = %0d",colors.size()); $display("colors array = %p",colors); endfunction endclass program assoc_array_randomization; assoc_array pkt; initial begin pkt = new(); pkt.randomize(); pkt.display(); end endprogram
Simulator Output
colors array size is = 3 colors array = '{RED:'hab, GREEN:'h92, YELLOW:'hb}