Constraint for consecutive_ones in a variable

I have a 32 bit variable, I want to write a constraint which constraints the number of consecutive ones that the variable can have.

The below constraint gives the maximum number of one that the variable can have. I want to have a constraint which limits the number of consecutive 1s to 4. The other bits could be 1/0. so the $countones can be greater than 4.
I created a function which can count the number of consecutive ones in a variable, but I cannot use that function in a constraint with input as variable as variable will be solved first and then the function and it causes constraint failure.

class random;
  rand bit [31:0] variable;

 constraint C1 {
  $countones(variable) <=4 ;
endclass
constraint CONSECUTIVE_ONES { $countones( variable & ( variable << 1 ) ) inside { [1:4] } ; }

That won’t work if there multiple sets of 4 consecutive bits.

you can scan the variable to make sure there are never 5 consecutive bits set.

constraint C4 { foreach (variable[i]) i>4 -> variable[i-:5] != '1; }

Hi Dave,
Just to confirm using constraint CONSECUTIVE_ONES

I could possibly see variable as <28_1_N_0_with_non_consectuive_1s>_1111
but not something like 11_0111101111_0111101111_0111101111

Hi Dave,
I tried to execute your code in EDA playground with VCS and it’s giving more than 5 1’s consecutively.

And i tried as below and it’s working

constraint c_values{

foreach(addr[i]){
 
  if(i>3){
        
   {addr[i], addr[i-1],addr[i-2], addr[i-3],addr[i-4]} != 5'b11111;
  // addr[i-:4] != 5'b11111;
  }
  
}

}

I like Dave’s method because it’s concise, but it had an off-by-one bug that allowed the 5 LSBs to be 5’b11111. Bug fix and full self-checking example here: Edit code - EDA Playground

@rabh Here is my version

class abc;
  rand bit[31:0] arr;
  
  constraint arr_c {
    foreach(arr[i]){
      if(i>=4) arr[i-:5] != '1;
      if(i>=0 && i<=3) arr[i] == 1;
    }
  
  }
    function void post_randomize();
        //foreach(arr[i,j]) 
    $display("value of array = %b",arr);
    endfunction   
     
      
endclass

module tb;
   abc abc_inst;
  initial begin 
    abc_inst = new();
    repeat(10)
    abc_inst.randomize();

  end
endmodule