# Magic square on system verilog

**URL:** <https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496>\
**Category:** SystemVerilog\
**Tags:** SystemVerilog\
**Created:** [September 5, 2019, 6:23am UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496 "2019-09-05T06:23:04Z")\
**Posts on this page:** 19\
**Page:** 1

<div class="post-metadata">

**Author:** ![rag123](https://verificationacademy.com/forums/letter_avatar_proxy/v4/letter/r/eada6e/32.png) [@rag123](https://verificationacademy.com/forums/u/rag123)\
**Post date:** [September 5, 2019, 6:23am UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/1 "2019-09-05T06:23:04Z")

</div>

Hi,

I am trying to write a program where the rows, columns, and diag of the matrix should be equal to 15. when i enabled the first contraint it seems i am getting some random value instead of 15 any idea why?

// Code your design here

```verilog
class magicsquare;
  
  rand bit [7:0] a [0:2][0:2];
  
  int i,j,k;
  
  constraint c1 {foreach (a[i,j]) 
    
    if (j==0) {a[i].sum() ==8'd15; } }
  
  function void display ();
                 $display ("The value of array is %p",a);
  endfunction
  
endclass

module test;
  magicsquare m1;
  
  
  initial begin
    m1=new ();
    m1.randomize();
    m1.display();
    
  end
  
endmodule

```

---

<div class="post-metadata">

**Author:** ![dave\_59](https://verificationacademy.com/forums/user_avatar/verificationacademy.com/dave_59/32/4499_2.png) [@dave\_59](https://verificationacademy.com/forums/u/dave_59)\
**Post date:** [September 5, 2019, 2:50pm UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/2 "2019-09-05T14:50:57Z")

</div>

_In reply to [rag123](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496):_

See [Constraint Randomization | Verification Academy](https://verificationacademy.com/forums/systemverilog/constraint-randomization#reply-54008)

---

<div class="post-metadata">

**Author:** ![rag123](https://verificationacademy.com/forums/letter_avatar_proxy/v4/letter/r/eada6e/32.png) [@rag123](https://verificationacademy.com/forums/u/rag123)\
**Post date:** [September 6, 2019, 5:00am UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/3 "2019-09-06T05:00:11Z")

</div>

_In reply to [dave\_59](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/2):_

Hi Dave,

I modified the code, but i dont see rows 2 and 3 is equal to 15.

// Code your design here

```verilog
class magicsquare;
  
  rand bit [7:0] a [0:2][0:2];
  rand bit [7:0] b [0:2][0:2];
  
  int i,j,k;
  
  constraint c1 {foreach (a[i,j]) 
    
  if (i==0) {a.sum() with (int'(item)) ==8'd15; } }
      
      constraint c2 {foreach (a[i,j])
    
        if (i==1){ a.sum() with (int'(item)) == 8'd15 ;}}
      
    
      
   // constraint c2 {foreach (a[i,j]) 
    
     // if (i==0) {a.sum() with (int'(item)) ==8'd15; } }
  
  function void display ();
                 $display ("The value of array is %p",a);
                    
  endfunction
  
endclass

module test;
  magicsquare m1;
  
  
  initial begin
    m1=new();
    m1.randomize();
    m1.display();
    
  end
  
endmodule

```

Expected output:

```auto
2 7 6
  9 5 1
  4 3 8

```

---

<div class="post-metadata">

**Author:** ![dave\_59](https://verificationacademy.com/forums/user_avatar/verificationacademy.com/dave_59/32/4499_2.png) [@dave\_59](https://verificationacademy.com/forums/u/dave_59)\
**Post date:** [September 6, 2019, 5:52am UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/4 "2019-09-06T05:52:44Z")

</div>

_In reply to [rag123](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/3):_

I believe you want

```verilog
constraint c1 {foreach (a[i,])
 if (i==0||i==1){ a[i].sum() with (int'(item)) == 8'd15 ;}

```

---

<div class="post-metadata">

**Author:** ![rag123](https://verificationacademy.com/forums/letter_avatar_proxy/v4/letter/r/eada6e/32.png) [@rag123](https://verificationacademy.com/forums/u/rag123)\
**Post date:** [September 7, 2019, 1:48am UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/5 "2019-09-07T01:48:24Z")

</div>

_In reply to [dave\_59](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/4):_

class magicsquare;

rand bit [7:0] a [0:2][0:2];

int i,j,k;

constraint c1 {foreach (a[i,])

```
if (i==0||i==1||i==2){ a[i].sum() with (int'(item)) == 8'd15 ;}}
  
constraint c2 {foreach (a[i,j]) 

    if (j==0||j==1||j==2){ a[j].sum() with (int'(item)) == 8'd15 ;}}
  
 // constraint c3 {foreach (a[i!=j]) 

 // { a[i!=j].sum() with (int'(item)) == 8'd15 ;}}

```

function void display ();  
$display (“The value of array is %p”,a);  
endfunction

endclass

program test;  
magicsquare m1;

initial begin  
m1=new();  
m1.randomize();  
m1.display();

end

endprogram

The value of array is ‘{’{'h8, 'h1, 'h6}, '{'h3, 'h5, 'h7}, '{'hf, 'h0, 'h0}}

Thanks Dave. This satisfies the row constraints, but some how the column constraint is not satisfied. Also i need the sum of elements 00,11,22 to be 15 as well. I tried something like this, but it doesnt seem to compile.

constraint c3 {foreach (a[i!=j])

```
     { a[i!=j].sum() with (int'(item)) == 8'd15 ;}}

```

---

<div class="post-metadata">

**Author:** ![sam33rs](https://verificationacademy.com/forums/letter_avatar_proxy/v4/letter/s/2bfe46/32.png) [@sam33rs](https://verificationacademy.com/forums/u/sam33rs)\
**Post date:** [October 20, 2019, 6:00am UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/6 "2019-10-20T06:00:29Z")

</div>

```verilog
constraint c {
  a.sum() with (item.index(1)==0 ? item : 0) == 15;//row0
  a.sum() with (item.index(1)==1 ? item : 0) == 15;//row1
  a.sum() with (item.index(1)==2 ? item : 0) == 15;//row2
  a.sum() with (item.index(2)==0 ? item : 0) == 15;//col0
  a.sum() with (item.index(2)==1 ? item : 0) == 15;//col1
  a.sum() with (item.index(2)==2 ? item : 0) == 15;//col2
  a.sum() with (item.index(1) == item.index(2) ? item : 0) == 15; //diag1
  a.sum() with ((item.index(1) + item.index(2) == 2) ? item : 0) == 15; //diag2
}

```

---

<div class="post-metadata">

**Author:** ![naveensv](https://verificationacademy.com/forums/user_avatar/verificationacademy.com/naveensv/32/2371_2.png) [@naveensv](https://verificationacademy.com/forums/u/naveensv)\
**Post date:** [October 22, 2019, 9:05am UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/7 "2019-10-22T09:05:37Z")

</div>

_In reply to [sam33rs](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/6):_

I see syntax errors with this code.  
Is it working for you?

```verilog
a.sum() with (item.index(1)==0 ? item : 0) == 15;//row0

```

Error - This type is illegal in this context [SystemVerilog].

Regards,  
Naveen

---

<div class="post-metadata">

**Author:** ![sam33rs](https://verificationacademy.com/forums/letter_avatar_proxy/v4/letter/s/2bfe46/32.png) [@sam33rs](https://verificationacademy.com/forums/u/sam33rs)\
**Post date:** [October 22, 2019, 5:48pm UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/8 "2019-10-22T17:48:28Z")

</div>

_In reply to [naveensv](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/7):_

Works for me.

---

<div class="post-metadata">

**Author:** ![prasadaddagarla](https://verificationacademy.com/forums/letter_avatar_proxy/v4/letter/p/8e8cbc/32.png) [@prasadaddagarla](https://verificationacademy.com/forums/u/prasadaddagarla)\
**Post date:** [February 27, 2020, 10:52pm UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/9 "2020-02-27T22:52:34Z")

</div>

_In reply to [sam33rs](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/9):_

> 

```verilog
constraint c {
a.sum() with (item.index(1)==0 ? item : 0) == 15;//row0
a.sum() with (item.index(1)==1 ? item : 0) == 15;//row1
a.sum() with (item.index(1)==2 ? item : 0) == 15;//row2
a.sum() with (item.index(2)==0 ? item : 0) == 15;//col0
a.sum() with (item.index(2)==1 ? item : 0) == 15;//col1
a.sum() with (item.index(2)==2 ? item : 0) == 15;//col2
a.sum() with (item.index(1) == item.index(2) ? item : 0) == 15; //diag1
a.sum() with ((item.index(1) + item.index(2) == 2) ? item : 0) == 15; //diag2
}

```

You can further simplify with a loop:

```verilog

class magicsquare;
 
  rand bit [7:0] a [0:2][0:2];
 
  int i,j,k;
 
  constraint c1 {

        foreach(a[i,j]) {
            a.sum with (item.index(1) == i ? int'(item): 0) == 15; // rows
            a.sum with (item.index(2) == j ? int'(item): 0) == 15; // cols
        }
        a.sum with (item.index(1) == item.index(2) ? int'(item) : 0) ==15; // diag1
        a.sum with ( (item.index(1) + item.index(2)==2) ? int'(item) : 0) ==15; // diag2
  }
 
  function void display ();
                 $display ("The value of array is %p",a);
  endfunction
 
endclass

```

---

<div class="post-metadata">

**Author:** ![regular\_joe](https://verificationacademy.com/forums/letter_avatar_proxy/v4/letter/r/ecb155/32.png) [@regular\_joe](https://verificationacademy.com/forums/u/regular_joe)\
**Post date:** [May 30, 2020, 3:37am UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/10 "2020-05-30T03:37:52Z")

</div>

I tried a different approach that involves matrix transpose. Its definitely much lengthier than the solutions described here, but this solution might scale better than the solution described above.

```verilog
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

```

---

<div class="post-metadata">

**Author:** ![BansariPatel](https://verificationacademy.com/forums/letter_avatar_proxy/v4/letter/b/e8c25b/32.png) [@BansariPatel](https://verificationacademy.com/forums/u/BansariPatel)\
**Post date:** [October 8, 2021, 5:52am UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/11 "2021-10-08T05:52:44Z")

</div>

_In reply to [sam33rs](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/11):_

class matrixsum;

rand bit [7:0] a [0:2][0:2];

int i,j,k;

constraint c1 {  
foreach(a[i,j]) {  
a.sum with (**item.index(1) == i ? int’(item): 0**) == 15; // rows  
a.sum with (**item.index(2) == j ? int’(item): 0**) == 15; // cols  
}  
a.sum with (**item.index(1) == item.index(2) ? int’(item) : 0**) ==15; // diag1  
a.sum with (**(item.index(1) + item.index(2)==2) ? int’(item) : 0**) ==15; // diag2  
}

function void display ();  
$display (“The value of array is %p” , a);  
endfunction

endclass  
module test;  
matrixsum m1;

initial begin  
repeat(3) begin  
m1=new();  
m1.randomize();  
m1.display();  
end  
end

endmodule

Here in bold syntax. what’s the requirement? and how it will work? I want to know the logic behind that 4 syntaxes. but why another value other than 12 and 15 is not applicable to get the sum as that replaced value of 15 in this code.

here, whats use of item.index(1) == item.index(2) and (item.index(1) + item.index(2)==2 and

```
    a.sum with (***item.index(1) == i ? int'(item): 0***) == 15; // rows
    a.sum with (***item.index(2) == j ? int'(item): 0***) == 15; // cols

 a.sum with ( ***item.index(1) == item.index(2) ? int'(item) : 0***) ==15; // diag1
 a.sum with ( ***(item.index(1) + item.index(2)==2) ? int'(item) : 0***) ==15; // diag2

```

here, why only index(1) & index(2) is taken why not others else ? give me satisfactory answers of my questions.

---

<div class="post-metadata">

**Author:** ![svq](https://verificationacademy.com/forums/letter_avatar_proxy/v4/letter/s/f475e1/32.png) [@svq](https://verificationacademy.com/forums/u/svq)\
**Post date:** [October 24, 2021, 6:51pm UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/12 "2021-10-24T18:51:35Z")

</div>

_In reply to [Bansari Patel](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/12):_

Because the matric is 2 dimensional. Here index(1) refers to row and index(2) refers to column

---

<div class="post-metadata">

**Author:** ![UVM\_geek](https://verificationacademy.com/forums/letter_avatar_proxy/v4/letter/u/d07c76/32.png) [@UVM\_geek](https://verificationacademy.com/forums/u/UVM_geek)\
**Post date:** [May 20, 2023, 3:31am UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/13 "2023-05-20T03:31:13Z")

</div>

Hi prasadaddagarla,

When I extended for 4x4 matrix all satisfies except diag1

> **[EDA Playground](https://edaplayground.com/x/TcA8)**
>
> Edit, save, simulate, synthesize SystemVerilog, Verilog, VHDL and other HDLs from your web browser.

{'{'h5, 'h3, 'h3, 'h4}, '{'h0, 'h7, 'h5, 'h3}, '{'h5, 'h3, 'h1, 'h6}, '{'h5, 'h2, 'h6, 'h2}}

How can we generalise this for nxn matrix?

Thanks !!!

---

<div class="post-metadata">

**Author:** ![dave\_59](https://verificationacademy.com/forums/user_avatar/verificationacademy.com/dave_59/32/4499_2.png) [@dave\_59](https://verificationacademy.com/forums/u/dave_59)\
**Post date:** [May 20, 2023, 6:08am UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/14 "2023-05-20T06:08:28Z")

</div>

_In reply to [UVM\_geek](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/14):_

The previous solutions are wrong. See [2D array constraint randomization | Verification Academy](https://verificationacademy.com/forums/systemverilog/2d-array-constraint-randomization#reply-110950)

The correct solution is

```verilog
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

```

---

<div class="post-metadata">

**Author:** ![UVM\_geek](https://verificationacademy.com/forums/letter_avatar_proxy/v4/letter/u/d07c76/32.png) [@UVM\_geek](https://verificationacademy.com/forums/u/UVM_geek)\
**Post date:** [May 20, 2023, 6:32am UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/15 "2023-05-20T06:32:57Z")

</div>

Thank you so much DAVE !!!

---

<div class="post-metadata">

**Author:** ![curious\_verifier](https://verificationacademy.com/forums/letter_avatar_proxy/v4/letter/c/97f17d/32.png) [@curious\_verifier](https://verificationacademy.com/forums/u/curious_verifier)\
**Post date:** [July 12, 2023, 1:49am UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/16 "2023-07-12T01:49:40Z")

</div>

Hi Dave,

I tried your solution in simulator to understand: a.sum(row) with (row.sum(col)  
and it give error saying col not defined.

Error-[IND] Identifier not declared  
testbench.sv, 10  
Identifier ‘col’ has not been declared yet. If this error is not expected,  
please check if you have set `default\_nettype to none.  
Instance stack trace:  
$unit /apps/vcsmx/vcs/S-2021.09//etc/uvm-1.2/src/uvm.sv, 1

Error-[IND] Identifier not declared  
testbench.sv, 10  
Identifier ‘col’ has not been declared yet. If this error is not expected,  
please check if you have set `default\_nettype to none.  
Instance stack trace:  
$unit /apps/vcsmx/vcs/S-2021.09//etc/uvm-1.2/src/uvm.sv, 1

---

<div class="post-metadata">

**Author:** ![dave\_59](https://verificationacademy.com/forums/user_avatar/verificationacademy.com/dave_59/32/4499_2.png) [@dave\_59](https://verificationacademy.com/forums/u/dave_59)\
**Post date:** [July 12, 2023, 5:30pm UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/17 "2023-07-12T17:30:42Z")

</div>

_In reply to [curious\_verifier](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/17):_

Please see [2D array constraint randomization | Verification Academy](https://verificationacademy.com/forums/systemverilog/2d-array-constraint-randomization#reply-111002)

---

<div class="post-metadata">

**Author:** ![nayakp](https://verificationacademy.com/forums/letter_avatar_proxy/v4/letter/n/9fc348/32.png) [@nayakp](https://verificationacademy.com/forums/u/nayakp)\
**Post date:** [January 18, 2024, 4:37pm UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/18 "2024-01-18T16:37:45Z")

</div>

the above link is not working : " Oops! That page doesn’t exist or is private."

---

<div class="post-metadata">

**Author:** ![dave\_59](https://verificationacademy.com/forums/user_avatar/verificationacademy.com/dave_59/32/4499_2.png) [@dave\_59](https://verificationacademy.com/forums/u/dave_59)\
**Post date:** [January 18, 2024, 4:39pm UTC](https://verificationacademy.com/forums/t/magic-square-on-system-verilog/36496/19 "2024-01-18T16:39:36Z")

</div>

There was a bug in the forum software we are using that has been addressed. Please refresh this page before clicking on the link
