Question

Java language only **Mandatory Rules** Put Descriptive comments on the code displayed on top of previous...

Java language only

**Mandatory Rules**

Put Descriptive comments on the code displayed on top of previous comments alreadys displayed

On Top of Code write summary of what code will do in comments

At the end of the code have the output in comment form

I Will thumbs up good Work thanks!

public class MagicSquare {

static int[][] createMagicSquare(int square[][]) {

// Initialize position for 1

int i = 3/2;

int j = 3-1;

// One by one put all values in magic square

for (int num=1; num <= 9; )

{

if (i==-1 && j==3) //3rd condition

{

j = 3-2;

i = 0;

}

else

{

// 1st condition helper if next number

// goes to out of square's right side

if (j == 3)

j = 0;

// 1st condition helper if next number

// is goes to out of square's upper side

if (i < 0)

i=3-1;

}

if (square[i][j]!=0) //2nd condition

{

j -= 2;

i++;

continue;

}

else

square[i][j] = num++; //set number

j++; i--; //1st condition

}

return square;

}

static boolean checkSquare(int[][] square) {

// calculate the sum of

// the prime diagonal

int sum = 0;

for (int i = 0; i < 3; i++)

sum = sum + square[i][i];

// For sums of Rows

for (int i = 0; i < 3; i++) {

int rowSum = 0;

for (int j = 0; j < 3; j++)

rowSum += square[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 < 3; i++) {

int colSum = 0;

for (int j = 0; j < 3; j++)

colSum += square[j][i];

// check if every column sum is

// equal to prime diagonal sum

if (sum != colSum)

return false;

}

return true;

}

public static void main(String args[]) {

int square[][]=new int[3][3];

//assigning all values in the array to 0

for(int i=0;i<3;i++) {

for(int j=0;j<3;j++) {

square[i][j]=0;

}

}

square=createMagicSquare(square);

// Print magic square

System.out.println("The magic square is:");

for (int i=0; i<3; i++)

{

for (int j=0; j<3; j++)

System.out.format("%3d ", square[i][j]);

System.out.println("");

}

if(checkSquare(square))

System.out.println("The given square is Lo Shu Magic Square...");

else

System.out.println("The given square is not a Lo Shu Magic Square...");

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

/**

* A magic square is an order of n^2 number in a matrix form the range of 1 to n^2, in which sum of element of all row, column and diagonal have same constant value.

The first number will be stored at position (n/2, n-1) i.e. (1,2). The next number will store at position (i-1, j+1) i.e. (0,0), we can consider each row & column as "circular array" [note this point] i.e. they wrap around.

1. position of next number is determine by decrementing row number of previous number by 1, and incrementing the column number of previous number by 1. At any time, if the determine row position becomes -1, it will wrap around to n-1.

Similarly, if the calculated column position becomes n, it will wrap around to 0.

2. If the magic square already contains a number at the calculated position, calculated column position will be decremented by 2, and calculated row position will be incremented by 1.

3. If the calculated row position is -1 & calculated column position is n, the new position would be: (0, n-2).

*

*/

public class MagicSquare {

static int[][] createMagicSquare(int square[][]) {

//This is the default position which we need to initialize i.e. (1,2)

// Initialize position for 1

int i = 3 / 2;

int j = 3 - 1;

//We have total 9 place (3*3) to fill the value in square matrix, so iterate 9 times only.

// One by one put all values in magic square

for (int num = 1; num <= 9;)

{

//This is condition when both row and column is out of bound i.e. new position will be (0, n-2) where n is 3 in this question

if (i == -1 && j == 3) // 3rd condition

{

j = 3 - 2;

i = 0;

}

else

{

//As I explained above that consider this as a circular and it is not the condition of (-1, n) where n=3, then once column reach to out of bound make it 0.  

// 1st condition helper if next number

// goes to out of square's right side

if (j == 3)

j = 0;

//As I explained above that consider this as a circular and it is not the condition of (-1, n) where n=3, then once row reach to out of bound make it n-1.

// 1st condition helper if next number

// is goes to out of square's upper side

if (i < 0)

i = 3 - 1;

}

//If the magic square already contains a number at the calculated position, calculated column position will be decremented by 2,

//and calculated row position will be incremented by 1.

if (square[i][j] != 0) // 2nd condition

{

j -= 2;

i++;

continue;

}

else

//if the magic square contains 0 then set the square equal to num and increment the num.

square[i][j] = num++; // set number

//The position of next number is determined by decrementing row number of previous number by 1, and incrementing the column number

//of previous number by 1. At any time, if the calculated row position becomes -1, it will wrap around to n-1. Similarly, if the

//calculated column position becomes n, it will wrap around to 0.

j++;

i--; // 1st condition

}

return square;

}

static boolean checkSquare(int[][] square) {

//Here we are adding the diagonal value and calculating the sum of diagonal which should be equal to sum of each row and each column

// calculate the sum of

// the prime diagonal

int sum = 0;

for (int i = 0; i < 3; i++)

sum = sum + square[i][i];

//Here 2 loop require to check whether each row is equal to the diagonal sum or not, if not equal then its not magic square and return false

// For sums of Rows

for (int i = 0; i < 3; i++) {

int rowSum = 0;

for (int j = 0; j < 3; j++)

rowSum += square[i][j];

// check if every row sum is

// equal to prime diagonal sum

if (rowSum != sum)

return false;

}

//Here 2 loop require to check whether each column is equal to the diagonal sum or not, if not equal then its not magic square and return false

// For sums of Columns

for (int i = 0; i < 3; i++) {

int colSum = 0;

for (int j = 0; j < 3; j++)

colSum += square[j][i];

// check if every column sum is

// equal to prime diagonal sum

if (sum != colSum)

return false;

}

return true;

}

public static void main(String args[]) {

int square[][] = new int[3][3];

// assigning all values in the array to 0

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

square[i][j] = 0;

}

}

square = createMagicSquare(square);

// Print magic square

System.out.println("The magic square is:");

for (int i = 0; i < 3; i++)

{

for (int j = 0; j < 3; j++)

System.out.format("%3d ", square[i][j]);

System.out.println("");

}

if (checkSquare(square))

System.out.println("The given square is Lo Shu Magic Square...");

else

System.out.println("The given square is not a Lo Shu Magic Square...");

}

}

/**

* output of given problem:

*

* The magic square is:

2 7 6

9 5 1

4 3 8

The given square is Lo Shu Magic Square...

*/

Add a comment
Know the answer?
Add Answer to:
Java language only **Mandatory Rules** Put Descriptive comments on the code displayed on top of previous...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I'm having trouble sorting this square matrix (a 2d array that has number of rows and...

    I'm having trouble sorting this square matrix (a 2d array that has number of rows and same number of column n x n) using row-wise approach in C programming. Please help me program this in C to sort it using row-wise approach, here is the code: #include <stdio.h> #define MAX 100 int main() { int mat[MAX][MAX]; int i, j, m, n; int rowsum, columnsum, diagonalsum; int k; int magic = 0; int transpose[MAX][MAX]; printf("Enter the # of rows and columns...

  • Use basic java for this after importing PrintWriter object You will make a simple Magic Square...

    Use basic java for this after importing PrintWriter object You will make a simple Magic Square program for this Java Programming Assignment. Carefully read all the instructions before beginning to code. It is also required to turn in your pseudocode or a flowchart along with this program. Here are the instructions: At the beginning of the program, briefly describe to the user what a Magic Square Matrix is (described further on), and then allow them to enter “start” to begin...

  • composed the following java code to read a string from a text file but receiving compiling...

    composed the following java code to read a string from a text file but receiving compiling errors. The text file is MyNumData.txt. Included the original java script that generated the output file. Shown also in the required output results after running the java program. I can't seem to search for the string and output the results. Any assistance will be greatly appreciated. import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class Main {   public static void main(String[] args) {     System.out.print("Enter the...

  • Can someone explain this code with comments I am supposed to dispay an array an add...

    Can someone explain this code with comments I am supposed to dispay an array an add each columns and add each row An application uses a two-dimensional array declared as follows: int[][] days = new int[29][5]; a. Write code that sums each row in the array and displays the results. b. Write code that sums each column in the array and displays the results. class TwoDimensionalArrayDemo { public static void main( String[] arg ) { int[][] days = new int[29][5];...

  • need help editing or rewriting java code, I have this program running that creates random numbers...

    need help editing or rewriting java code, I have this program running that creates random numbers and finds min, max, median ect. from a group of numbers,array. I need to use a data class and a constructor to run the code instead of how I have it written right now. this is an example of what i'm being asked for. This is my code: import java.util.Random; import java.util.Scanner; public class RandomArray { // method to find the minimum number in...

  • I am using C++ Write a program to determine if a gird follows the rules to...

    I am using C++ Write a program to determine if a gird follows the rules to be classified as a Lo Shu Magic Square. The Lo Shu Magic Square is a grid with 3 rows and 3 columns shown in figure below. The Lo Shu Magic Square has the following properties: The grid contains the numbers 1 through 9 exactly. The sum of each row, each column, and each diagonal all add up to the same number. This is shown...

  • I am given an input file, P1input.txt and I have to write code to find the...

    I am given an input file, P1input.txt and I have to write code to find the min and max, as well as prime and perfect numbers from the input file. P1input.txt contains a hundred integers. Why doesn't my code compile properly to show me all the numbers? It just stops and displays usage: C:\> java Project1 P1input.txt 1 30 import java.io.*; // BufferedReader import java.util.*; // Scanner to read from a text file public class Project1 {    public static...

  • Help pls! and kindly explain how you do this as well. Thaank you Write a program...

    Help pls! and kindly explain how you do this as well. Thaank you Write a program to test whether a square is a 3x3 magic square. A magic square is a grid with 3 rows and 3 columns, like the figure below. A magic square has the following properties: the grid contains only the numbers 1 through 9 the sum of each row, each column, and each diagonal all add up to the same number Notes: I have provided the...

  • Can you help me with this code in Java??? import java.util.Scanner; public class Main { public...

    Can you help me with this code in Java??? import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int rows = 3; int columns = 4; int[][] arr = new int[rows][columns]; for(int i = 0; i < rows; ++i) { for(int j = 0; j < columns; ++j) { System.out.println("Enter a value: "); arr[i][j] = scan.nextInt(); } } System.out.println("The entered matrix:"); for(int i = 0; i < rows; ++i) { for(int j...

  • Provide comments for this code explaining what each line of code does import java.util.*; public class...

    Provide comments for this code explaining what each line of code does import java.util.*; public class Chpt8_Project {    public static void main(String[] args)       {        Scanner sc=new Scanner(System.in);        int [][]courses=new int [10][2];        for(int i=0;i<10;i++)        {            while(true)            {                System.out.print("Enter classes and graduation year for student "+(i+1)+":");                courses[i][0]=sc.nextInt();                courses[i][1]=sc.nextInt();                if(courses[i][0]>=1...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT