Skip to content

Commit 185d879

Browse files
[N-0] refactor 289
1 parent 174a4fb commit 185d879

File tree

1 file changed

+8
-26
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+8
-26
lines changed

src/main/java/com/fishercoder/solutions/_289.java

Lines changed: 8 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -28,41 +28,23 @@ public void gameOfLife(int[][] board) {
2828
int height = board.length;
2929
int width = board[0].length;
3030
int[][] next = new int[height][width];
31+
int[][] directions = {{-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}};
3132

3233
for (int i = 0; i < board.length; i++) {
3334
for (int j = 0; j < board[0].length; j++) {
3435
int liveCellsCount = 0;
3536
//count all its live cells
3637

37-
if (j + 1 < width && board[i][j + 1] == 1) {
38-
liveCellsCount++;//right cell
39-
}
40-
if (j - 1 >= 0 && board[i][j - 1] == 1) {
41-
liveCellsCount++;//left cell
42-
}
43-
if (i + 1 < height && board[i + 1][j] == 1) {
44-
liveCellsCount++;//down cell
45-
}
46-
if (i - 1 >= 0 && board[i - 1][j] == 1) {
47-
liveCellsCount++;//up cell
48-
}
49-
if (i - 1 >= 0 && j - 1 >= 0 && board[i - 1][j - 1] == 1) {
50-
liveCellsCount++;//up left cell
51-
}
52-
if (i - 1 >= 0 && j + 1 < width && board[i - 1][j + 1] == 1) {
53-
liveCellsCount++;//up right cell
54-
}
55-
if (i + 1 < height && j - 1 >= 0 && board[i + 1][j - 1] == 1) {
56-
liveCellsCount++;//down left cell
57-
}
58-
if (i + 1 < height && j + 1 < width && board[i + 1][j + 1] == 1) {
59-
liveCellsCount++;//down right cell
38+
for (int[] dir : directions) {
39+
int x = i + dir[0];
40+
int y = j + dir[1];
41+
if (x >= 0 && y >= 0 && x < height && y < width && board[x][y] == 1) {
42+
liveCellsCount++;
43+
}
6044
}
6145

6246
if (board[i][j] == 1) {
63-
if (liveCellsCount > 3 || liveCellsCount < 2) {
64-
next[i][j] = 0;
65-
} else {
47+
if (liveCellsCount <= 3 && liveCellsCount >= 2) {
6648
next[i][j] = 1;
6749
}
6850
} else if (board[i][j] == 0) {

0 commit comments

Comments
 (0)