user3547407
user3547407

Reputation: 187

cyclic randomization for a group of variables in SystemVerilog

I'm trying to randomize 3 different variables in system verilog but in a cyclic fashion. What I mean is, I have the following 3 variables

rand int a;
rand int b;
rand int c;

constraint c_a{
  a inside {1,2};     
}
constraint c_b{
  b inside {1,2,3,4,5,6};
}
constraint c_c{
  c inside {1,2,3}
}

With the above constraints, there are a total of 36 combinations of all the 3 variables (2x6x3).

But if we run a loop of 36, like so :

repeat(36) begin
  this.randomize(a,b,c);
  $display("%d   %d   %d", a,b,c);
end

we wont hit all the possible combinations as some combinations might be repeated. Hence I'm looking to find a way to hit all those combinations by running the loop exactly 36 times.

I wrote a brute force way to do this by declaring another rand variable to represent each combination and using randc on it like so :

int a;
int b;
int c;
randc int k;

constraint c_k{
  k inside {[1:36]};
}

repeat(36) begin
  this.randomize(k);
  // randomizing variable 'a' to one of the 2 values.
  if(k<9)
    a = 1;
  else
    a = 2;
  // randomizing variable 'b' to one of the 6 values.
  case(k)
    1,2,3,19,20,21 : b = 1;
    4,5,6,22,23,24 : b = 2;
    7,8,9,25,26,27 : b = 3;
    //
    //   finishing the sequence
    // 
  endcase  

  case(k)
     // similar case statement for the final variable
  endcase

  $display("%d, %d, %d", a,b,c);
end

The above way works fine, but to me it seemed kind of a hectic way (which also cannot be applied for large combinations) and hence wondering if there is a more elegant method to achieve this.

Thanks for you help.

Upvotes: 2

Views: 2074

Answers (1)

dave_59
dave_59

Reputation: 42788

What you can do is concatenate your variables into a packed struct and make that a randc variable.

module top;
class A;
    typedef struct packed {
    bit [1:0]   a;
    bit [2:0]   b;
    bit [1:0]   c;
    } abc_t;
randc abc_t k;
constraint c_a{
  k.a inside {1,2};     
}
constraint c_b{
  k.b inside {1,2,3,4,5,6};
}
constraint c_c{
  k.c inside {1,2,3};
}
endclass
   A h = new;
   initial 
     repeat(40) begin
       h.randomize();
       $display("%0p",h.k);
     end
endmodule

Be aware that the total number of bits allowed for a randc variable may be limited by the simulator

Upvotes: 5

Related Questions