Constraint Randomization

Hi,

I need help in one of the constraint patterns. Basically the code i have will print a triangle left sided, but what i wanted in turn is the right sided triangle. Any help is appreciated.



Left sided:
1 0 0
1 1 0
1 1 1 

Right sided:
0 0 1
0 1 1
1 1 1

// Code your testbench here
// or browse Examples

class triangle;
 
  rand bit [7:0] a [0:2][0:2];
 
  int i,j,k;
 
  
  
  
  constraint c {

    foreach (a[i])
      foreach (a[i][j])
        if (j<=i)
           a[i][j] ==1;
    else a[i][j] ==0;
}
  
 
 
  function void display ();
                 $display ("The value of array is %p",a);
  endfunction
 
endclass
 
module test;
  triangle m1;
 
 
  initial begin
    m1=new ();
    m1.randomize();
    m1.display();
 
  end
 
endmodule

In reply to rag123:



foreach(a[i])
    foreach (a[i][j]) 
      if(i==0 && j == 3-1)  a[i][j] ==1;  //use size instead of hardcoded value of 3 as matrix is 3x3 
    else if( i>0 && (i != 3-1  && (j > 0))) a[i][j] ==1;
      else if (i == 3-1 ) a[i][j] ==1;
      else a[i][j] == 0 ;
    

Simply use left shift operator in constraint and in post-randomize method negate each index value.
Something like this : (arr[i][j] == (2 << i) - 1)

In reply to rag123:
A couple of comments about your code

  • There is no need to declare the variables i,j, and k. The foreach statement declares them implicitly for you.
  • Use one foreach statement with the indexes separated with a comma “,” as I show in my solution below.
  • The syntax you use in the nested
    foreach[i][j]
    is illegal according to the SystemVerilog LRM. It not always clear that you meant for the first index to be a constant and not meant to be an iterator. If you really needed to nest, you would have to write it as
foreach(a[i]) foreach(a[,j])
  • Always test the return value from
    randomize()
class triangle;
 
  rand bit [7:0] a [0:2][0:2];
 
  constraint c {
    foreach (a[i,j])
      a[i][j] == (j>=$size(a)-i-1);
  }
 
  function void display ();
                 $display ("The value of array is %p",a);
  endfunction
endclass 
 
module test;
  triangle m1;
 
   initial begin
    m1=new ();
    assert(m1.randomize());
    m1.display();
  end
endmodule

In reply to dave_59:

Thanks Dave :) yes i agree and will fix it.

constraint a_c {
  foreach (a[i,]) 
    {foreach (a[,j]) 
       {if (i+j == 1'b0 || i+j == 1'b1) 
         {a[i][j]==0;} 
          else {a[i][j]==1;}
       }
    }
}