Randomize an array using constraints such that no number in the array repeats more than twice

In reply to dave_59:

Hello Sir,
I think there are some mistakes in your code.

  1. Question demands to have a constraint that will make sure that any particular digit does not appear more than 2 times consecutively.
    But the line you have written it’s assuring that any digit does not occur consecutively.
  2. Another condition is like 2 3 4 is valid but 2 3 4 5 is not. Your code is checking something
    else. ( digit[i-1]+1 != digit[i]+2 ) - why has this condition been made ?

I tried to make tiny little changes (using the if statement) in your code. Neither am I sure of my code is accurate and covers all cases nor am I getting your code.
Please look into it.


module top;

  class A;
    rand bit [3:0] digit[10];
    constraint c  { 
      foreach (digit[i]){
        // decimal 1st
        digit[i] <10; 
        // repetition 2nd
        //i > 0 -> digit[i-1] != digit[i] ;
        if(i>1 && digit[i]==digit[i-1])
          digit[i]!=digit[i-2];
        // sequence 3rd
        //i > 1 -> digit[i-2] != digit[i-1]+1 &&  digit[i-1]+1 != digit[i]+2 ;
        if(i>2 && digit[i]==digit[i-1]+1 && digit[i]==digit[i-2]+2)
          digit[i]!=digit[i-3]+3;
       //if(i>)
      }
    }
  endclass
 
  A a=new;
      initial repeat (5) begin
    assert(a.randomize());
    $display("%p ",a.digit);
  end
 
endmodule

vsim -voptargs=+acc=npr

run -all

'{5, 2, 3, 0, 3, 2, 9, 3, 3, 1}

'{2, 8, 9, 9, 8, 6, 9, 2, 2, 3}

'{2, 1, 5, 1, 2, 0, 9, 9, 4, 6}

'{8, 3, 1, 0, 9, 3, 6, 5, 0, 2}

'{3, 1, 6, 3, 7, 1, 6, 8, 6, 3}

exit

End time: 07:33:47 on Oct 14,2022, Elapsed time: 0:00:01

Errors: 0, Warnings: 0