Interview question on constraints

In reply to sdeepak.v:

I’m not sure if I’m following your question but assuming you want every 5 elements of the valid array to have no more than 3 1’s, you can do something like this (I probably not the optimal solution), also I’m not sure why you need 32-bit variables if you want only 1 or 0 values


class packet;
   rand bit valid [$];
   rand bit [4:0] valid5;
   constraint valid_c {
      valid.size() == 65;
      $countones(valid5) == 3;
   }
   function void post_randomize();
      bit temp[$];
      foreach(valid5[j]) begin
         temp.push_back(valid5[j]);
      end
      for(int i = 0; i < valid.size(); i = i+5) begin
         valid[i:i+4] = temp;
         temp.shuffle();
      end
   endfunction

endclass

module tb;
initial begin
packet pkt;
pkt = new();

$display("------------------------------------");
// repeat(2) begin
  if(!pkt.randomize()) $fatal(1, "Randomize Failed");
// $display("\taddr-size = %0d data-size = %0d",pkt.addr.size(),pkt.data.size());
  foreach(pkt.valid[i]) $display("valid[%0d] = %b ", i, pkt.valid[i]);
$display("------------------------------------");

end
endmodule

HTH,
-R

1 Like