Using sum() to Calculate the Sum of a 2D Array

In reply to dave_59:

Hi Dave,

Basically, I would like to know how to put a constraint on the sum of a 2d array.



module p1;
  
  class c1;
    
    
    rand int m [2][2];
    
    rand int x;
    

    constraint c1{
      foreach(m[i,j])
        m[i][j] inside {[-1:1]};
    }
    

    constraint c1_2{
      x == m.sum with (item.sum with (item));
      
      //only works in in vcs 
      //x == m.sum();
    }
    

    constraint c1_3{
      x == 2;
      
    }
    
   
    
  endclass
  
  c1 c1_h;
  
  logic [7:0] n [2][2] = '{ '{5, 10}, '{15, 20} };
  int n_sum;
  
  initial begin
    c1_h = new();
    
    if(c1_h.randomize())
      $display("m is %p", c1_h.m);
    
    
    n_sum = n.sum with (item.sum with (item));
    
    //the sum of 2d array can be calculated this way
    $display("n_sum is %d", n_sum);
    
  end
  
endmodule

I am wondering why my code doesn’t work? Is there a more convenient way to put a constraint on the sum of a 2d array?

Thank you.