Assignment #1 Magic Square Electronic submission due by Monday, 10/1, 11:00pm. B
ID: 3754700 • Letter: A
Question
Assignment #1
Magic Square
Electronic submission due by Monday, 10/1, 11:00pm.
Bring your typed, written report to class Tuesday, 10/2.
Concepts
Review: class design, 2-dimensional arrays, etc.
Get your problem-solving brain cells firing!
Problem
A magic square of order N is an N x N arrangement of the integers from 1 to N2 into rows and columns such that the rows, columns, and the 2 diagonals add up to the same, specific number: N(N2 + 1)/2. Here is an example of a 3 x 3 Magic Square:
Notice that each row, each column, and the 2 diagonals add up to 15 [ 3(32 + 1)/2 ]. You are going to write a program that allows the user to enter an odd integer and create a Magic Square of that size.
Specification
Implementation:
Your solution will only deal with Magic Squares of odd order N. The algorithm you must use to fill the cells is as follows:
Starting from the middle row, last column, with the number 1, the fundamental movement for filling the squares is diagonally right and down, one step at a time.
If a filled square is encountered, move to the left one square instead, then continue as before.
When a move would leave the Magic Square, wrap around.
You are to create a class according to this public specification:
+ OddMagicSquare(int n) : construct a MagicSquare of order n. If n is not a positive odd number, throw an appropriate exception.
+ String toString(): returns a String representation of this MagicSquare. The String should be made up of "lines" of numbers, one line for each row. No special formatting is required, but if you are interested, you can investigate the static method String.format().
+ static boolean isMagic(int[][] a) : a static method that is passed in a 2 - dimensional array and returns true if it is a Magic Square, false if not. (This method should not throw an exception under any circumstances.)
+ static void main(String[] args) : the method that contains the user interface and runs the program.
Not extra credit, but an extra challenge... A given magic square can be flipped horizontally, flipped vertically or rotated 90 degrees clockwise or counterclockwise and still remain a magic square. For this extra challenge, add methods to accomplish one or more of these. These "update" or "mutator" methods should change the state of the object (change the data stored in the array) to correspond to the updated configuration.
User Interface:
Your program will have a text-based interface, using the Scanner class for keyboard input and println for output. The program should prompt the user for an odd integer. If it is valid, then create a MagicSquare and display it. If the user input is invalid, then display a helpful message.
The program should repeat until the user enters an exit code to quit (like 0). Ensure that the user knows what that exit code is!
Suggestions
You always need to fully understand a problem before you can design a program to solve it. Try drawing a 5x5 magic square on paper following the instructions above. Then, test it by summing up at least one row, one column and one diagonal to see if it works.
You will have success if you code and test in pieces. I would recommend getting your class methods working first. Then work on the user interface.
Think carefully about the isMagic method. It is the most challenging. Keep in mind that the method should work properly for ANY value passed into the parameter. When you design the testing, consider all possible values that might be used when the method is called.
class OddMagicSquare <data members are for you to decide, but you must use a 2-dimensional array to hold the integers>+ OddMagicSquare(int n) : construct a MagicSquare of order n. If n is not a positive odd number, throw an appropriate exception.
+ String toString(): returns a String representation of this MagicSquare. The String should be made up of "lines" of numbers, one line for each row. No special formatting is required, but if you are interested, you can investigate the static method String.format().
+ static boolean isMagic(int[][] a) : a static method that is passed in a 2 - dimensional array and returns true if it is a Magic Square, false if not. (This method should not throw an exception under any circumstances.)
+ static void main(String[] args) : the method that contains the user interface and runs the program.
Not extra credit, but an extra challenge... A given magic square can be flipped horizontally, flipped vertically or rotated 90 degrees clockwise or counterclockwise and still remain a magic square. For this extra challenge, add methods to accomplish one or more of these. These "update" or "mutator" methods should change the state of the object (change the data stored in the array) to correspond to the updated configuration.
357 492Explanation / Answer
import java.io.*;
import java.util.Scanner;
class MagicSquare
{
int[][] magicSquare;
// Function to generate odd sized magic squares
void OddMagicSquare(int n)
{
if(n%2==0)
{
System.out.println("Invalid Input");
}
else
{
magicSquare = new int[n][n];
// Initialize position for 1
int i = n/2;
int j = n-1;
// One by one put all values in magic square
for (int num=1; num <= n*n; )
{
if (i==-1 && j==n) //3rd condition
{
j = n-2;
i = 0;
}
else
{
//1st condition helper if next number
// goes to out of square's right side
if (j == n)
j = 0;
//1st condition helper if next number is
// goes to out of square's upper side
if (i < 0)
i=n-1;
}
//2nd condition
if (magicSquare[i][j] != 0)
{
j -= 2;
i++;
continue;
}
else
//set number
magicSquare[i][j] = num++;
//1st condition
j++; i--;
}
// print magic square
/* System.out.println("The Magic Square for "+n+":");
System.out.println("Sum of each row or column "+n*(n*n+1)/2+":");
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
System.out.print(magicSquare[i][j]+" ");
System.out.println();
} */
}
}
public String toString()
{
int n=magicSquare.length;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
System.out.print(magicSquare[i][j]+" ");
System.out.println();
}
return ("");
}
static boolean isMagic(int mat[][])
{
int N=mat.length;
// calculate the sum of
// the prime diagonal
int sum = 0;
for (int i = 0; i < N; i++)
sum = sum + mat[i][i];
// For sums of Rows
for (int i = 0; i < N; i++) {
int rowSum = 0;
for (int j = 0; j < N; j++)
rowSum += mat[i][j];
// check if every row sum is
// equal to prime diagonal sum
if (rowSum != sum)
return false;
}
// For sums of Columns
for (int i = 0; i < N; i++) {
int colSum = 0;
for (int j = 0; j < N; j++)
colSum += mat[j][i];
// check if every column sum is
// equal to prime diagonal sum
if (sum != colSum)
return false;
}
return true;
}
// driver program
public static void main (String[] args)
{
// Works only when n is odd
Scanner scan=new Scanner(System.in);
MagicSquare m=new MagicSquare();
int n = scan.nextInt();
do {
System.out.println("Exit Code 0");
m.OddMagicSquare(n);
System.out.println(m);
n=scan.nextInt();
}while(n>0);
}
}