How to generate a pattern 110011001100 using constraint

I am using this piece of code ,but its not happening.
class packet;

bit pattern[$];
byte a;

constraint c1 {
foreach (a[i])
if(i % 2 == 0)
pattern.push_back(00);
else
pattern.push_back(11);
}
endclass

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

repeat(5) begin
pkt.randomize();
foreach(pkt.a[i])
$display(“pattern =%0p”,pkt.pattern);

end
endmodule

In reply to big123:

Here is how I tried it, and seems to be working.


class rand_bit_pattern;
  rand bit bit_pattern[];
  
  constraint size_arr_C { bit_pattern.size inside {[3:99]}; }
  constraint pattern_C { 
    foreach(bit_pattern[idx]) {
      if(idx%4 == 0 || (idx%4==1)) bit_pattern[idx]==1;
      if(idx%4 == 2 || (idx%4==3)) bit_pattern[idx]==0;
    }
  }
  
  

  function print();
    
    foreach(bit_pattern[i])
      $write("%0b", bit_pattern[i]);
    
    $write("\n");
  endfunction
endclass


module test;
  rand_bit_pattern o = new();
  initial begin
    o.randomize();
    o.print();
  end
endmodule

In reply to disturbedWolf:
Thanks for the solution .
Can you please enlighten me the approach towards it .It will be really helpfull

In reply to big123:

In reply to disturbedWolf:
Thanks for the solution .
Can you please enlighten me the approach towards it .It will be really helpfull

My approach is what we call “hardcoded”. I am assuming that the pattern that you need to generate is given, and if it needs to be changed, you ll create a new class and override the constraint with the new one.

Now, for the code that you have, I dont understand why you need both “a” and the “pattern” queue both. You should just be able to use a single queue/array and randomize.

As for the constraints in my example, size_arr_C will limit the size of the dynamic array bit_pattern. Then, pattern_C will be used to get the desired pattern, i.e for a byte, 1100, so mod 0,1 will give you 1 and another 1, and then %2,3 will be set to 0.
Rest of the code is just infrastructure and presentation.

You can also randomize just the size of the pattern, and put the “known pattern” in post_randomize. Just have a rand var which will determine the size and then new your pattern in post_randomize.

In reply to disturbedWolf:

Thanks for such information . very much needful

This could be more flexible over generating any pattern. Setting the number of repetition with inline constraint.

bit wr_rd;
  bit [7:0] cnt;
  bit prev_wr_rd;
  rand bit [7:0] rep;
  
  function void pre_randomize();
    if(cnt < (rep-1)) cnt = cnt +1;
    else cnt =0;
    prev_wr_rd = wr_rd;
  endfunction
  
  function void post_randomize();
    wr_rd = (cnt==0) ? ~prev_wr_rd : wr_rd;
  endfunction