I tried a different approach that involves matrix transpose. I basically tried to solve the magic square problem (including the constraints on both the diagonals as well). Hope that helps!
class magic_square#(int grid_size=4);
rand bit[4:0] rand_array[grid_size][grid_size];
rand bit[4:0] rand_array_transpose[grid_size][grid_size];
rand bit[4:0] diagonal_0[grid_size];
rand bit[4:0] diagonal_1[grid_size];
rand int unsigned rand_sum;
constraint magic_square_cnstr {
rand_sum >= 0;
rand_sum <= 8'hFF;
foreach(rand_array[i]) {
unique{rand_array[i]};
rand_array[i].sum() with (int'(item)) == rand_sum;
}
foreach(rand_array[i,j]) {
rand_array_transpose[j][i] == rand_array[i][j];
if (i==j) {
diagonal_0[i] == rand_array[i][j];
}
if ((i+j) == grid_size-1) {
diagonal_1[i] == rand_array[i][j];
}
}
foreach(rand_array_transpose[i]) {
unique{rand_array_transpose[i]};
rand_array_transpose[i].sum() with (int'(item)) == rand_sum;
}
foreach(rand_array[i,j]) {
foreach(rand_array[i1,j1]) {
if ((i!=i1) && (j!=j1)) {
rand_array[i][j] != rand_array[i1][j1];
}
}
}
diagonal_0.sum() with (int'(item)) == rand_sum;
diagonal_1.sum() with (int'(item)) == rand_sum;
}
function post_randomize();
string row_print;
$display("Solving for grid_size:0x%0x sum:0x%0x", grid_size, rand_sum);
foreach (rand_array[row]) begin
row_print = {row_print,$sformatf("%p \n", rand_array[row])};
end
$display ("%s", row_print);
endfunction // post_randomize
endclass // magic_square
module magic_square();
initial begin
magic_square #(4) ms = new();
assert(ms.randomize());
end
endmodule // magic_square