MAGIC SQUARE JAVA PROGRAM I have tried using a one dimensional array for this pr
ID: 3663778 • Letter: M
Question
MAGIC SQUARE JAVA PROGRAM
I have tried using a one dimensional array for this problem but I am running into some heavy issues. I have seen examples of two dimensional magic square programs online, but I have been trying to do it in one-dimension considering my professor said it could be done.
Program Specification An n x n matrix that is filled with the whole numbers 1, 2, 3, .. n2 is a magic square if the sum of the elements in each row, in each column, and in the two diagonals is the same value Here is a magic square where n = 3 4 Write a program that reads n2 numbers from standard input and tests whether they form a magic square when put into matrix form. The value of n is NOT an input to the program; n must be determined from the number of inputs. For example, the input that creates the example matrix above is 8163 5749 2. The output is a single word, "true" if the input produces a magic square, "false" otherwise. Your program may assume that each input token is a whole number The program must verify: Th e proper number of input values was provided. 2.Each of the numbers between 1 and n occurs exactly once in the input. When the numbers are arranged in a matrix, the sum of the rows, columns, and diagonals must be the same value .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
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.