-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMagicSquare.java
More file actions
71 lines (60 loc) · 1.4 KB
/
MagicSquare.java
File metadata and controls
71 lines (60 loc) · 1.4 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
69
70
71
abstract class MagicSquare {
protected int[][] square;
protected int n;
protected int magicNumber;
public MagicSquare(int n) {
this.square = new int[n][n];
this.n = n;
this.magicNumber = (int) (n * (Math.pow(n, 2) + 1)) / 2;
}
public static int getMagicNumber(int n) {
return (int) (n * (Math.pow(n, 2) + 1)) / 2;
}
abstract void generate();
public boolean isMagic() {
//Somme des lignes
int sum;
for (int i = 0; i < square.length; i++) {
sum = 0;
for (int j = 0; j < square.length; j++) {
sum = sum + square[i][j];
}
if (sum != this.magicNumber) {
return false;
}
}
//Somme des colonnes
for (int i = 0; i < square.length; i++) {
sum = 0;
for (int j = 0; j < square.length; j++) {
sum = sum + square[j][i];
}
if (sum != this.magicNumber) {
return false;
}
}
//Somme des diagonales
sum = 0;
int sum2 = 0;
for (int i = 0; i < square.length; i++) {
for (int j = 0; j < square.length; j++) {
if (i == j) {
sum = sum + square[i][j];
sum2 = sum2 + square[i][this.square.length - 1 - j];
}
}
}
if(sum != this.magicNumber || sum2 != this.magicNumber) {
return false;
}
return true;
}
public void display() {
for (int i = 0; i < this.square.length; i++) {
for (int j = 0; j < this.square.length; j++) {
System.out.print("[" + this.square[i][j] + "]");
}
System.out.println();
}
}
}