-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomMagicSquare.java
More file actions
53 lines (44 loc) · 1.02 KB
/
RandomMagicSquare.java
File metadata and controls
53 lines (44 loc) · 1.02 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
import java.util.ArrayList;
public class RandomMagicSquare extends MagicSquare {
public RandomMagicSquare(int n) {
super(n);
}
public void generate() {
while(!this.isMagic()) {
this.fill();
}
this.display();
}
private void fill() {
ArrayList<Integer> possibilities = this.randomSequence();
int cpt = 0;
for (int i = 0; i < this.square.length; i++) {
for (int j = 0; j < this.square.length; j++) {
this.square[i][j] = possibilities.get(cpt);
cpt++;
}
}
}
private ArrayList<Integer> randomSequence() {
ArrayList<Integer >numbers = new ArrayList<Integer>();
int cpt = (int) Math.pow(this.n, 2);
int random;
int sum = 0;
while (cpt > 0) {
random = 1 + (int)(Math.random() * Math.pow(this.n, 2));
if (!numbers.contains(random)) {
numbers.add(random);
cpt--;
sum = sum + random;
if (cpt % this.n == 0) {
if (sum != this.magicNumber) {
cpt = (int) Math.pow(this.n, 2);
numbers.clear();
}
sum = 0;
}
}
}
return numbers;
}
}