Aaron Yang
Aaron Yang

Reputation: 23

How can I create a dynamic array with different random values in random size?

Interview question: I have a systemverilog based class as following:

class A;
rand n;
constraint c:{n>=10 &&n<=15};
bit [31:0] arr[];
randc [31:0] data;
endclass

In this case 'n' is the size of the dynamic array arr. And the question is how to write a method to create the array so that all the elements in this array is different from each other.

So the problem is randc type can only make sure each time I instantiate the class, I get a different value, but how can I store those value in an array like this? Any help is appreciated.

P.S. There may be mistakes in the class and it is editable.

Upvotes: 2

Views: 9911

Answers (3)

Karan Shah
Karan Shah

Reputation: 1992

Without unique, you can do something like this :

class T;
  randc bit [31:0] x;
endclass

class A;
  rand bit [31:0] arr[];
  local T temp;

  function void post_randomize();
    foreach (arr[i])
    begin
      void'(temp.randomize());
      arr[i] = temp.x;
    end 
    void'(temp.randomize());  
  endfunction

  constraint size_con { arr.size() inside {[10:15]}; }
endclass

Upvotes: 1

ChetanJoshi
ChetanJoshi

Reputation: 71

You can generate unique random pattern of a dynamic array with just using some tight constraint.I try to give some solution for the same.I have also add one code example for the same. hope it will help you.

class A;

  rand int a[];

  constraint generate_unique_dyn_array {
  foreach( a[ii] )
   {
       foreach( a[jj] )
       {
            if( ii != jj )
                 a[ii] != a[jj] ;
       }
   }
}
endclass

Upvotes: 0

dave_59
dave_59

Reputation: 42698

You want the unique constraint.

class A;
  rand bit [31:0] arr[];

  constraint arr_size { arr.size() inside {[10:15]}; }
  constraint arr_uniq { unique {arr}; }

endclass

Upvotes: 4

Related Questions