Randomizing 2D int arrays producing unexpected results

I am trying to make sure that the sum of elements in the arr is 10.
But somehow the randomization happening such a way that some of the elements in arr is negative (because of type int).
I will get the correct answer if I kept the constraint option

arr[i][j] < 10;

Is there any way to avoid this issue without the above constraint ?

class sample;
  rand int arr[2][4];
  constraint x {
    foreach (arr[i, j]) {
      arr[i][j] > 0;
      //arr[i][j] < 10;
  constraint xy {
    arr.sum(row) with (row.sum(col) with ( int'(col) )) == 10;
    //arr.sum() with (item.sum() ) == 10;

module top;
  sample s = new();
  int sum;
  initial begin
    foreach (s.arr[i]) begin
      $display("%p", s.arr[i]);
    foreach (s.arr[i,j]) begin
      sum = sum+s.arr[i][j];
    $display("Sum =%0d", sum);

result in eda playground is

'{1111106533, 65323945, 787707370, 750105959} 
'{110764343, 273178680, 1188421186, 8359290} 
Sum =10

There are 2 things you need to do

  • Declare the array elements with an unsigned type. Either int unsigned or bit [N:0]
  • The sum() needs to be calculated in a context with no overflow. With 8 elements in the array, you need at least 3 extra bits.
class sample;
  rand bit[3:0] arr[2][4]; // implicitly constrained to values 0-15 
  constraint xy {
    arr.sum(row) with (row.sum(col) with ( 8'(col) )) == 10;

See How does .sum() operate in a constraint

I understood the issue.
Thanks Dave.