Saturday, July 18, 2020

Generating RANDC without using the keyword

In many interviews people ask this question,
how can we reproduce functionality of RANDC without using the keyword in the variable declaration.


About the code:

Here we used a variable 'v' which ranges from 3:0 covering 0-15 values.
Let us say we need to limit the range to 10.
We used a queue to place the value generated by 'v' in post_randomize().
Since the constraint unique { v,v_q } ensures unique values in v and v_q, v will not generate the same value again, therefore matching the behavior of randc.
Once queue reaches size of 10, we clear it.

Here is the piece of code which does the work.

CODE:

class test;
  rand bit [3:0] v;
  bit [3:0] v_q[$];

  constraint c_v { unique {v,v_q};
                            v inside {[1:10]};
                 }

  function void post_randomize();
    v_q.push_back(v);
    if(v_q.size() == 10) v_q.delete();
  endfunction: post_randomize

  function void display();
    $display("V:%0d",v);
  endfunction: display

endclass

module top;
  test t;

  initial begin
    t = new;
    repeat(20) begin
      void'(t.randomize());
      t.display();
    end
  end
endmodule: top


Results :
CPU time: .234 seconds to compile + .310 seconds to elab + .310 seconds to link
Chronologic VCS simulator copyright 1991-2019
Contains Synopsys proprietary information.
Compiler version P-2019.06-1; Runtime version P-2019.06-1; Jul 18 23:48 2020
V:3
V:5
V:8
V:9
V:7
V:10
V:4
V:6
V:1
V:2
V:10
V:7
V:6
V:5
V:4
V:8
V:1
V:2
V:9
V:3
V C S S i m u l a t i o n R e p o r t

No comments:

Post a Comment

Constraint to have N elements distributed in M bins

Code to distribute N elements into M bins, you add unique keyword to have each bin will have unique number of elements. class test; param...