Hello!

Today I am going to show you how can one write Java program that produces magic square of any odd size.

Magic square has equal number of columns and rows and Integers on each row ,column,diagonal are equal when they are summed up. All Integers are distinct that is there are no duplicates.

This magic square works as long as size of square(two-dimensional array) is odd that is 3,5,7,9,11 and so on.

The output:

If we do magic square of size 9 that is :

The result will be :

Today I am going to show you how can one write Java program that produces magic square of any odd size.

Magic square has equal number of columns and rows and Integers on each row ,column,diagonal are equal when they are summed up. All Integers are distinct that is there are no duplicates.

This magic square works as long as size of square(two-dimensional array) is odd that is 3,5,7,9,11 and so on.

import java.util.Arrays; class MagicSquare { private int oldColumn = 0; private int oldRow = 0; private int column = 0; private int row = 0; private int squareLength = 0; private int[][] magicSquare; private void adjustRow() { oldRow = row--; if (row < 0) { row = squareLength - 1; } } private void adjustColumn() { oldColumn = column++; if (column >= squareLength) { column = 0; } } private void setNumber(int number) { adjustIfOccuppiedCell(); magicSquare[row][column] = number; } private void adjustIfOccuppiedCell() { if (magicSquare[row][column] != 0) { row = ++oldRow; column = oldColumn; } } private void doMagicSquare(int msLength) { this.squareLength = msLength; magicSquare = new int[msLength][msLength]; column = msLength / 2; magicSquare[row][column] = 1; for (int i = 2; i <= (msLength * msLength); i++) { adjustRow(); adjustColumn(); setNumber(i); } } private void printMagicSquare() { for (int i = 0; i < magicSquare.length; i++) { int[] row = magicSquare[i]; System.out.println(Arrays.toString(row)); } } public static void main(String args[]) { MagicSquare ms = new MagicSquare(); ms.doMagicSquare(5); ms.printMagicSquare(); } }

The output:

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

If we do magic square of size 9 that is :

ms.doMagicSquare(9);

The result will be :

[47, 58, 69, 80, 1, 12, 23, 34, 45] [57, 68, 79, 9, 11, 22, 33, 44, 46] [67, 78, 8, 10, 21, 32, 43, 54, 56] [77, 7, 18, 20, 31, 42, 53, 55, 66] [6, 17, 19, 30, 41, 52, 63, 65, 76] [16, 27, 29, 40, 51, 62, 64, 75, 5] [26, 28, 39, 50, 61, 72, 74, 4, 15] [36, 38, 49, 60, 71, 73, 3, 14, 25] [37, 48, 59, 70, 81, 2, 13, 24, 35]

## No comments:

## Post a Comment