Repository navigation
Expand file tree
/
Copy pathMagicSquare.java
More file actions
68 lines (63 loc) · 1.53 KB
/
Copy pathMagicSquare.java
File metadata and controls
68 lines (63 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package math;
/**
* Create a Magic square. A square where all rows, columns and both diagonals
* have the same constant sum.
*
* Magic Constant (the sum value) = n*(n^2+1)/2.
*
* Link: http://www.geeksforgeeks.org/magic-square/
*
* @author shivam.maharshi
*/
public class MagicSquare {
// This approach works only for odd values of n.
public static int[][] get(int n) {
int[][] a = new int[n][n];
// First number will always be present at this place.
int row = n / 2;
int col = n - 1;
int count = n * n;
int val = 0;
while (count > 0) {
// Wrap excess values around.
if (row == -1) {
row = n - 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 (a[row % n][col % n] != 0) {
col -= 2;
row++;
continue;
}
/*
* If the calculated row position is -1 & calculated column position
* is n, the new position would be: (0, n-2).
*/
if (row == -1 && col == n) {
row = 0;
col = n - 2;
continue;
}
a[row % n][col % n] = ++val;
row--;
col++;
count--;
}
return a;
}
public static void print(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
MagicSquare.print(get(4));
}
}