Magic squares

posted by: Ms. Martin 12 January 2011 No Comment

Read about 2D arrays.

A magic square is an nxn array of squares which has the following properties:
Each integer from 1 to n2 appears in the array exactly once; and
The sum of each row is equal to the sum of each column is equal to the sum of each diagonal.
Here is an example of a 3×3 magic square:
2 7 6
9 5 1
4 3 8
If you add up any row, colum, or diagonal, the sum of the numbers will be 15.
Magic squares come in all sizes–they are not all 3×3.

Write the method isMagicSquare(int[][] square) that takes an nxn array of ints and returns true if the array contains a magic square and false otherwise. You may assume that the input to isMagicSquare has the same number of rows as it does columns.

isMagicSquare needs to work on ALL squares, not just the example or 3×3 squares.

Here is some code that you might find useful:

public class Main {
	public static void main(String[] args) {
		int[][] test = { {2, 7, 6},
				 {9, 5, 1},
				 {4, 3, 8} };
		printMagicSquare(test);
	}

	public static void printMagicSquare(int[][] arr) {
		int length = arr.length;
		for (int row = 0; row < length; row++) {
			for (int col = 0; col < length; col++) {
				System.out.print(arr[row][col] + " ");
			}
			System.out.println();
		}
	}
}

1 Star2 Stars3 Stars4 Stars5 Stars (10 votes, average: 3.00 out of 5)
Loading ... Loading ...

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>