-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLife.java
99 lines (77 loc) · 1.78 KB
/
Life.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
public class Life {
private int[][] current;
private int[][] next;
private final int ROWS;
private final int COLS;
public Life(int rows, int cols) {
ROWS = rows;
COLS = cols;
current = new int[ROWS][COLS];
}
private int neighborsAlive(int row, int col) {
int sum = 0;
int currentRow;
int currentCol;
int currentNum;
for (int i = 1; i >= -1; i--) {
for (int j = 1; j >= -1; j--) {
currentRow = row - i;
currentCol = col - j;
if (row == currentRow && col == currentCol) {
// do not check current cell
} else {
// for checked cells. separate IFs allow all bidirectional wrapping
if (currentRow < 0) {
// wrap around to bottom row
currentRow = ROWS - 1;
}
if (currentCol < 0) {
// wrap around to rightmost row
currentCol = COLS - 1;
}
if (currentRow >= ROWS) {
// wrap around to top row
currentRow = 0;
}
if (currentCol >= COLS) {
// wrap around to leftmost row
currentCol = 0;
}
currentNum = current[currentRow][currentCol];
if (currentNum == 1) {
sum++;
}
}
}
}
return sum;
}
public void calcNext() {
int neighbors;
next = new int[ROWS][COLS];
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
neighbors = neighborsAlive(i, j);
if (neighbors == 3) {
next[i][j] = 1;
} else if (neighbors == 2) {
next[i][j] = current[i][j];
} else {
next[i][j] = 0;
}
}
}
// set current equal to next for next iteration
current = next;
}
public void toggleAlive(int row, int col) {
if (current[row][col] == 0) {
current[row][col] = 1;
} else if (current[row][col] == 1) {
current[row][col] = 0;
}
}
public int[][] getCurrentState() {
return current;
}
}