Magic squares. An n × n matrix that is filled with the numbers 1, 2, 3, ..., n2
ID: 3624635 • Letter: M
Question
Magic squares. An n × n matrix that is filled with the numbers 1, 2, 3, ..., n2 is a magic square if the sum ofthe elements in each row, in each column, and in the two diagonals is the same value. For example,
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
Write a program that reads in n2 values from the keyboard and tests whether they form a magic square
when arranged as a square matrix. You need to test three features:
• Did the user enter n2 numbers for some n?
• Do each of the numbers 1, 2, ..., n2 occur exactly once in the user input?
• When the numbers are 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, test whether all numbers between 1 and n2 are present. Then compute
the row, columns, and diagonal sums. Implement a class Square with methods
public void add(int i)
public boolean isMagic()
Explanation / Answer
/************************************************************************* * Compilation: javac MagicSquare.java * Execution: java MagicSquare N * * Generates a magic square of order N. A magic squares is an N-by-N * matrix of the integers 1 to N^2, such that all row, column, and * diagonal sums are equal. * * One way to generate a magic square when N is odd is to assign * the integers 1 to N^2 in ascending order, starting at the * bottom, middle cell. Repeatedly assign the next integer to the * cell adjacent diagonally to the right and down. If this cell * has already been assigned another integer, instead use the * cell adjacently above. Use wrap-around to handle border cases. * * * % java MagicSquare 3 * 4 9 2 * 3 5 7 * 8 1 6 * * % java MagicSquare 5 * 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 * * Limitations * ----------- * - N must be odd * *************************************************************************/ public class MagicSquare { public static void main(String[] args) { int N = Integer.parseInt(args[0]); if (N % 2 == 0) throw new RuntimeException("N must be odd"); int[][] magic = new int[N][N]; int row = N-1; int col = N/2; magic[row][col] = 1; for (int i = 2; iRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.