Given a 32 bit address field as a class member, write a constraint to generate a random value such that it always has 10 bits as 1 and no two bits next to each other should be 1. Please solve this I'm unable to proceed

class gen_rand;
  rand bit [31:0] value;
 
  
  constraint c1 { {$countones(value) ==10};
                 {value == s_addr(value)};
    
  }
  
  function bit [31:0] s_addr(bit [31:0] r);
    value =r;
    //if(value[30]&value[31]==0);
    for (int i = 0; i < 31; i++);
     (!(value[i] && value[i + 1]));
 endfunction
  
  function void display();
    $display("value in binary = %0b",value);
  endfunction
  
endclass

module top;
  initial begin
    gen_rand gn =new();
    for (int i=0;i<5;i++)begin
      gn.c1.constraint_mode(0);
    gn.randomize();
      //gn.c1.constraint_mode(0);
      //gn.disable_constraint();
      gn.display();end
  end
endmodule

This isn’t working. I’m getting the errors

See this about using functions in constraints: Regarding function in constraints

Use an iterative foreach constraint instead of a for loop.

constraint c1 { $countones(value) == 10;
                foreach(value[i]) i>0 -> !(value[i] && value[i + 1]);
}
1 Like

but I’m getting the output like this
value in binary = 11000011000111000101010100011
value in binary = 10101010101101110100011111010110
value in binary = 1011101111010100110110000000001
value in binary = 11011011110001000001011001001
value in binary = 110110011111000011000101101

Delete:

      gn.c1.constraint_mode(0);

and change i+1 to i-1

Hi @dave_59 , I still getting the error even after doing all the changes

xmsim: *E,RNDCNSTE (./testbench.sv,9|60): Randomization constraint has this error, which will cause the randomize function to return 0 and no new rand values will be set:
Out of bounds index in array reference, index 32 is not in the range [31:31].
gn.randomize();

This works for me:

class gen_rand;
  rand bit [31:0] value;
 
  constraint c1 {$countones(value) == 10;
                 foreach(value[i]) i>0 -> !(value[i] && value[i - 1]);
}
  function void display();
    $display("value in binary = %b",value);
  endfunction
  
endclass

module top;
  gen_rand gn =new();
  initial for (int i=0;i<5;i++) begin
    assert(gn.randomize());
    gn.display();
  end
endmodule
# value in binary = 10000100001001010010100001010100
# value in binary = 10010000101000010100101000010001
# value in binary = 01000010101000001010000010010101
# value in binary = 10010101000100100100101010000000
# value in binary = 01001001010100010010100100001000
1 Like

Thanks dave, it’s working