Magic square on system verilog

In reply to UVM_geek:

The previous solutions are wrong. See 2D array constraint randomization | Verification Academy

The correct solution is

class magicsquare;
  
  parameter int N = 4;
 
  rand bit [7:0] a [N][N];
  
  constraint c1 {
    foreach(a[i,j]) {
      a[i].sum(row) with (int'(row)) == 15; // rows
      a.sum(row) with (row.sum(col) with (col.index == j  ? int'(col) : 0))== 15; // cols
    }
      a.sum(row) with (row.sum(col) with (row.index==col.index ? int'(col) : 0 )) == 15; // diag1
    a.sum(row) with (row.sum(col) with (($size(a)-row.index-1)==col.index ? int'(col) : 0)) == 15; // diag2
  }
 
  function void display ();
    $display ("The value of array is");
    foreach(a[i]) $display("%p = ",a[i], a[i].sum(row) with (int'(row)));
    foreach(a[,j]) $write("%3d ",a.sum(row) with (row.sum(col) with (col.index == j  ? int'(col) : 0)));
    $display("\ndiag1 = ", a.sum(row) with (row.sum(col) with (row.index==col.index ? int'(col) : 0)));
    $display("diag2 = ",  a.sum(row) with (row.sum(col) with (($size(a)-row.index-1)==col.index ? int'(col) : 0)));
  endfunction
 
endclass
 
module test;
  magicsquare m1;
 
 
  initial begin
    m1=new();
    assert (m1.randomize());
    m1.display();
 
  end
 
endmodule