DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

shivaji has posted 4 posts at DZone. View Full User Profile

Java Program To Generate Magic Square

03.27.2012
| 20147 views |
  • submit to reddit
        A simple Java program to do this, can be easily rewritten in any language:

/* * Magic Square */
int order = 5;
for (int row = 0; row < order; row++) {
	for (int col = 0; col < order; col++) {
		int rowMatrix = (((order + 1) / 2 + row + col) % order);
		int colMatrix = (((order + 1) / 2 + row + order - col - 1) % order) + 1;
		System.out.print(((rowMatrix * order) + colMatrix) + "\t");
	}
	System.out.println();

}

Form a Square Matrix writing numbers 1 to nxn in sequence. Here n is the order of the Magic Square, say 5. 

1        2       3       4       5  
6        7       8       9      10
11      12      13      14      15
16      17      18      19      20
21      22      23      24      25

We are trying to identify the final Matrix from the above. Form two matrices, one for identifying the row and another to identify the column. 
4     5     1     2     3           3     2     1     5     4
5     1     2     3     4           4     3     2     1     5
1     2     3     4     5           5     4     3     2     1
2     3     4     5     1           1     5     4     3     2
3     4     5     1     2           2     1     5     4     3

You will see the middle column of the first Matrix starts with 1 and are in sequence. Columns on either side can be filled by subtracting and adding 1. The second Matrix is a mirror image.

Form the final Matrix by writing the number from initial Matrix in the corresponding row and column. For e.g 4, 3 (Step 2) = 18 (Step 1) 
18      22       1       10      14
24       3       7       11      20
5        9      13       17      21
6       15      19       23       2
12      16      25        4       8

The above steps are applicable for any order of the Magic Square!