Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

An n x n matrix that is filled with the numbers 1, 2, 3, …, n2 is a magic square

ID: 3640324 • Letter: A

Question

An n x n matrix that is filled with the 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. The MagicSquare class that follows holds a two-dimensional array, and the method isSquare() determines if the array matrix forms a magic square. There are three methods missing in the class that you must provide: rowSum(), colSum(), and diagSum()

/**
* MagicSquare - determines if array forms a magic square.
*/
public class MagicSquare
{
private int[][]square;

/**
* Constructor - passed in a square
*/
public MagicSquare(int[][]inSquare)
{
square = inSquare;
}

/**
* isMagic - determines if array forms a magic square.
*
* @return true if array is a magic square, false otherwise
*/
public boolean isMagic()
{
// test if two dimensions are the same
if (square.length != square[0].length)
{
return false; // not n x n
}
// test that all integers are represented
for (int num = 1; num <= square.length * square.length; num++)
{
boolean found = false;
for (int i = 0; i < square.length && found == false; i++)
{
for (int j = 0; j < square.length; j++)
{
if (square[i][j] == num)
{
found = true;
break; // out of inner for loop
}
}
}
if (found == false) // number not in array
{
return false;
}
}
// test that any row, column or diagonal did not match
if (rowSum() == -1 || colSum() == -1 || diagSum() == -1)
{
return false;
}
// test that the sums of rows, columns, and diagonals are same
if (rowSum() != colSum() || colSum() != diagSum())
{
return false;
}
// it is a magic square
return true;
}
/**
* rowSum - determines sum of rows.
*
* @return sum of rows if all the same, -1 otherwise
*/
public int rowSum()
{




















}
/**
* colSum - determines sum of columns.
*
* @return sum of columns if all the same, -1 otherwise
*/
public int colSum()
{


















}

/**
* diagSum - determines sum of the two diagonals.
*
* @return sum of two diagonals if the same, -1 otherwise
*/
public int diagSum()
{

























}
}

Explanation / Answer

/** * MagicSquare - determines if array forms a magic square. */ public class MagicSquare { private int[][]square; /** * Constructor - passed in a square */ public MagicSquare(int[][]inSquare) { square = inSquare; } /** * isMagic - determines if array forms a magic square. * * @return true if array is a magic square, false otherwise */ public boolean isMagic() { // test if two dimensions are the same if (square.length != square[0].length) { return false; // not n x n } // test that all integers are represented for (int num = 1; num
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote