Constraint Randomization of an Array : No consecutive bits should be one and No of ones should be 12

Hello,

I am trying to constraint a 32 bit array such that no of ones in the array are 12 and that they are non consecutive. Following code is giving inconsistent constraints failure, which is not making sense to me.

class packet;
  rand bit [31:0] addr;
  
  constraint addr_range { $countones(addr) == 12;
                         foreach(addr[i]) { 
                           if(i!=31 ) 
                           {
                             addr[i] && addr[i+1]==0; 
                           }  
                         }}
endclass

module soft_constr;
  initial begin
    packet pkt;
    pkt = new();
    repeat(2) begin
      pkt.randomize();
      $display("\taddr = %0d",pkt.addr);
    end
  end
endmodule 

EDA link :Problemo: Array-constraint - EDA Playground

Could some one explain why this code is not working ?
FYI: I do have a working solution for this problem, but I am curious to know what I am missing in this code.

Appreciate it.

Seems like you’re looking for


(addr[i] && addr[i+1]) == 0;

In reply to verif_gal:

Plug: Verilog Basics for SystemVerilog Constrained Random Verification | Verification Academy

In reply to sbellock:

Dang… Thank you for your response.

In reply to dave_59:

Registered. Thanks :)

In reply to verif_gal:

In general it’s a good practice to just use parentheses everywhere. Then you, and the reader of your code, don’t have to look up the operator precedence tables to figure out what’s going on.

In reply to sbellock:

I’m going to have to slightly disagree. Too many levels of parentheses may make things hard to read. If you are confident about the precedence, spacing might help readability.

Hi all,

I’m trying the same constraint spec with the following code and this is causing constraint failures. Could anyone let me know what is wrong with my code below :

class consecutive_ones;
  
  rand bit [31:0] test_ones;
  
  constraint test_ones_c {
    $countones(test_ones) == 12;
    foreach (test_ones[i]) { 
      if (i != 31) ( (test_ones[i] != test_ones[i+1]) );
    }  
  }
endclass : consecutive_ones

module test;
  initial begin
  	consecutive_ones my_obj;
    my_obj = new();
    my_obj.randomize();
    $display("Value is %b - # of 1s is %d",my_obj.test_ones,$countones(my_obj.test_ones));  
  end
endmodule

In reply to mavcdn:

The constraint


foreach (test_ones[i]) {if (i != 31) ( (test_ones[i] != test_ones[i+1]));}

means test_ones will have a repeating 2’b01 or 2’b10 pattern, and there will be 16 ones and 16 zeroes. That is in conflict with the other constraint

$countones(test_ones) == 12;

and so you get a constraint failure.

In reply to dave_59:

This link is not working.

In reply to anshushr:

Fixed.