The instructions specify \"The value of n is NOT an input to the program; n must
ID: 3863587 • Letter: T
Question
The instructions specify "The value of n is NOT an input to the program; n must be determined from the number of inputs. "
Coding Language: JAVA
Program Specification: An n x n matrix that is filled with the whole numbers 1, 2, 3, n 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 33: Write a program that reads n 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 8 1 6 3 57 49 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: The 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
import java.util.*;
class Magic{
public static boolean isMagicSquare(int[][] arr){
final int n=arr.length;
final int SquaredN=n*n;//square of n
final int M=(n*n*(n*n+1)/2)/n;
int RowSum=0, ColumnSum=0, PrimaryDiagonalSum=0, SecondaryDiagonalSum=0;//store row sum,solumn sum etc
boolean[] vis= new boolean[n*n];//to mark elements
for(int row=0; row<n; row++){
RowSum=0;
ColumnSum=0;
for(int col=0; col<n; col++)
{
if(arr[row][col]<1 || arr[row][col]>SquaredN) return false;
if(vis[arr[row][col]-1]==true) return false;
vis[arr[row][col]-1]=true;
RowSum += arr[row][col];
ColumnSum += arr[col][row];
}
PrimaryDiagonalSum += arr[row][row];
SecondaryDiagonalSum += arr[row][n-row-1];
if(RowSum!=M || ColumnSum!=M) return false;//if row sum and column sum not equal to M return false
}
if(PrimaryDiagonalSum!=M || SecondaryDiagonalSum!=M) return false;//if diagonal sum not equal to M return false
return true;
}
public static void main(String []args){
int arr[]={8,1,6,3,5,7,4,9,2};
int n=(int) Math.sqrt(arr.length);
int[][] a=new int[n][n];
// System.out.println("Enter Matrix");
int k=0;
for (int i=0;i<n ;i++ )
{
for (int j=0;j<n ;j++ )
{
a[i][j]=arr[k++];
System.out.print(a[i][j]+" ");
}
System.out.println(" ");
}
System.out.println(isMagicSquare(a));
}
}
===========================================================
Output:
8 1 6
3 5 7
4 9 2
true
=============================================================
Let me know of you have any problem
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.