954,518 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

magic square

how can i create a magic square using jcreator..
help me please..

kring08
Newbie Poster
3 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

Check the internet for the definition of a magic square and then post some code

javaAddict
Nearly a Senior Poster
Team Colleague
3,329 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 448
 

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.
*must be an 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; i <= N*N; i++) {
if (magic[(row + 1) % N][(col + 1) % N] == 0) {
row = (row + 1) % N;
col = (col + 1) % N;
}
else {
row = (row - 1 + N) % N;
// don't change col
}
magic[row][col] = i;
}

// print results
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (magic[i][j] < 10) System.out.print(" "); // for alignment
if (magic[i][j] < 100) System.out.print(" "); // for alignment
System.out.print(magic[i][j] + " ");
}
System.out.println();
}

}
}

kring08
Newbie Poster
3 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

And your question? The code seems to work

javaAddict
Nearly a Senior Poster
Team Colleague
3,329 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 448
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: