-
-
Notifications
You must be signed in to change notification settings - Fork 611
/
GameofLife.java
60 lines (56 loc) · 1.67 KB
/
GameofLife.java
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
package problems.medium;
/**
* Created by sherxon on 1/28/17.
*/
public class GameofLife {
public void gameOfLife(int[][] a) {
if (a == null || a.length == 0)
return;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
int count = count(a, i, j);
if (isAlive(a, i, j) && count < 2)
a[i][j] = -1;
else if (isAlive(a, i, j) && count > 3)
a[i][j] = -1;
else if (isAlive(a, i, j))
a[i][j] = 1;
else if (!isAlive(a, i, j) && count == 3)
a[i][j] = -2;
}
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] == -1)
a[i][j] = 0;
else if (a[i][j] == -2)
a[i][j] = 1;
}
}
}
boolean isAlive(int[][] a, int i, int j) {
if (i < 0 || j < 0 || i >= a.length || j >= a[i].length)
return false;
return a[i][j] == 1 || a[i][j] == -1;
}
int count(int[][] a, int i, int j) {
int count = 0;
if (isAlive(a, i - 1, j - 1))
count++;
if (isAlive(a, i - 1, j))
count++;
if (isAlive(a, i - 1, j + 1))
count++;
if (isAlive(a, i, j - 1))
count++;
if (isAlive(a, i, j + 1))
count++;
if (isAlive(a, i + 1, j - 1))
count++;
if (isAlive(a, i + 1, j))
count++;
if (isAlive(a, i + 1, j + 1))
count++;
return count;
}
}