Question on Array.Sum() Method , generate a n*n matrix such that there is only one 1's in a coloumn

In reply to CPU_Verif:
A couple of problems with the use of the foreach statement. You do not declare the iterator variables separately like you would in a for loop. They are implicitly declared and iterate over each array dimension. That creates problems with this illegal code that is accepted by some tools, especially when you have declared “i” as a separate variable

foreach (array[i]) begin
  foreach (array[i][j]) begin
    ...

More than one set of brackets is not allowed in a foreach loop declaration. It’s not clear if you are trying to declare an new implicit iterator “i” or use a previously declared variable.

The code below works for me on 2 simulators on EDAPlayground. The other two have bugs dealing with the sum method operating on 2-D arrays. You can work around that by using another foreach loop and creating a helper array that accumulates the sum from previous elements lie a fibonacci series.

class my_array;
  rand bit[4:0] array[4][5];
 
//This is first constraint limiting value of each item
constraint array_item_val {
  foreach (array[i,j]) { // for each row,column in array
    array[i][j] inside {[0:1]}; // each element is either 0/1
  }
}
 
constraint array_col_sum {
  foreach (array[,j]) {
    array.sum() with (int'(item[j])) == 1; // col max sum is 1
  }
}
 
function void display();
  foreach (array[i]) begin
    foreach (array[,j]) begin // correct way of nesting two loops
      $write(" %d ",array[i][j]);
    end
    $display("\n");
  end
endfunction
 
endclass
 
module my_array_randomization;
my_array ma;
 
initial begin
  ma = new();
  assert(ma.randomize());
  ma.display();
end
endmodule