Magic Squares A n x n matrix that is filled with numbers 1, 2, 3….n2. The sum of the…
- User
Magic Squares
A n x n matrix that is filled with numbers 1, 2, 3….n2. The sum of the elements in each row, column and the two diagonals is the same value. Write a program that reads in n2 values from the keyboard and tests to see if they form a magic square when arranged in a square matrix. You need to test for three conditions: Did the user enter n2 numbers for some n? Do each of the numbers 1, 2, 3….n2 occur exactly once in the user input? When put into a square, are the sums of the rows, columns and diagonals equal to each other?
IF the size of the input is a square, then test whether all numbers between 1 and n2 are present. Then compute the row, column and diagonal sums. Implement a class Square with methods public void add(int i) public boolean isMagic() This algorithm only works if n is odd. Place a 1 in the middle of the bottom row. Put the number 2 (we will call it k) at the top of the next column. Then follow this pattern : place k+1 into the square to the right and down, wrapping around the borders. However if the square to the right and down has already been filled or if you are in the lower right corner, then you must move to the square straight up instead. Here is a 5 x 5 version that follows this algorithm.
11 18 25 2 9 10 12 19 21 3 4 6 13 20 22 23 5 7 14 16 17 24 1 8 15
Write a program whose input is the number n and whose output is the magic square of order n if n is odd. Implement a class MagicSquare with a constructor that constructs the square and a toString method that returns a representation of the square.
- Assistant