Interview question on constraint



class A;
  
  rand bit[4:0]  array[10];
  rand bit[4:0] num1,num2;
  
  constraint C1 { foreach(array[i]) foreach(array[j]) {if(i!=j) array[i]!= array[j];}}
    constraint C2 {num1 !=num2; num1<10;num2<10;}
    
    function void post_randomize();
                 $display("post_randomize: num1=%d, num2=%d",num1,num2);
                 array[num1]=array[num2];
                 
                 endfunction
    
    function print();
      foreach(array[i]) begin
        $display("arr[%d]=%d",i,array[i]);
        foreach(array[j]) 
          if(array[i]==array[j] && i!=j) $display("array[%d] and array[%d] matches",i,j);
    
      end
      			
                 endfunction
endclass


module tb;
  
  A a=new();
  initial begin
    assert(a.randomize());
    a.print();
  end
  
  
endmodule

In reply to burra thanuja:

Bellow is simple sollution i have written for the above problem

class my_rand;
  rand bit [5:0] a[10];
  rand int b,c;
  
  constraint sum_new {
    solve b,c before a;
    foreach(a[i]){
      if((i == b )|| (i==c) )
        (a.sum() with(int'((item == a[i]))) ) == 2;
      else
        (a.sum() with(int'((item == a[i]))) ) == 1;
    }
  }
  constraint n1{
    b inside {[0:9]};
    c inside {[0:9]};
    c != b;
    
  }
      
   
endclass
module mod ();
  initial
    begin
      my_rand me;
      me = new();
      me.randomize();
      $display("%p",me.a);
      
    end
  
endmodule
1 Like

You can get the address question with below code.
It’s working 100%.

Array = '{'h0, 'h1, 'h2, 'h2, 'h3, 'h6, 'h7, 'h8, 'hb, 'he}

class ABC;
rand bit [3:0] array[10]; 

    constraint a_c { 
                        foreach(array[i]) { 
                            if(i>0) { 
                                if(i == 3) 
                                    array[i] == array[i-1]; 
                                else 
                                    array[i] > array[i-1];
                            }

                        }
    } 
endclass                      
    
    module tb; 

        initial begin 
            ABC abc; 
                abc = new(); 
                abc.randomize(); 
          $display("Array = %p", abc.array);
              end 
    endmodule