SV Array Constraint Question

Write a constraint to generate dynamic array of 60 elements. Each element can have value 0/1/2/3/4. Each of these above values should be present no more than 15 times in the array. Element 0 can be repeated while 1/2/3/4 are not allowed to repeat consecutively.

Below is my solution for this question. Is there a further optimal way to solve it?

class sample;
  rand int arr[60];
  
  
  
  constraint range_con{
    foreach(arr[i])
      arr[i] inside {[0:4]};
  }
  
  constraint no_conseq_zero{
    foreach(arr[i]){
      if(i>=1){
        if(arr[i-1]!=0) arr[i]!=arr[i-1]; 
      }
    }
      
  }
        
        constraint quant{
          arr.sum() with (int'(item==0))<=15;
          arr.sum() with (int'(item==1))<=15;
          arr.sum() with (int'(item==2))<=15;
          arr.sum() with (int'(item==3))<=15;
          arr.sum() with (int'(item==4))<=15;
          
        }
endclass
      
      module top;
        
        sample s = new();
        
        initial begin
          repeat(1) begin
            s.randomize();
            $write("%p,",s.arr);
          end
          
        end
      endmodule

In reply to totochan1985:

Your constraint no_conseq_zero has a simple mistake. Did you test it?

Also arr[60] is a fixed sized array, not a dynamic array.

In reply to dave_59:

In reply to totochan1985:
Your constraint no_conseq_zero has a simple mistake. Did you test it?
Also arr[60] is a fixed sized array, not a dynamic array.

class sample;
  rand int arr[];
  
  constraint arr_size{
    arr.size()==60; 
  }
  
  constraint range_con{
    foreach(arr[i])
      arr[i] inside {[0:4]};
  }
  
  constraint no_conseq_zero{
    foreach(arr[i]){
      
      (i>0 && arr[i-1]!=0) -> arr[i]!=arr[i-1]; 
      
    }
      
  }
        
        constraint quant{
          arr.sum() with (int'(item==0))<=15;
          arr.sum() with (int'(item==1))<=15;
          arr.sum() with (int'(item==2))<=15;
          arr.sum() with (int'(item==3))<=15;
          arr.sum() with (int'(item==4))<=15;
          
        }
endclass

Does this look better? Have fixed the no_conseq_zero constraint.

1 Like