-
Notifications
You must be signed in to change notification settings - Fork 6
/
289. Game of Life.js
59 lines (55 loc) · 1.22 KB
/
289. Game of Life.js
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
/**
* @param {number[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var gameOfLife = function (board) {
var m = board.length;
if (m < 0) {
return [];
}
var n = board[0].length;
var newBoard = [];
for (var i = 0; i < m + 2; i++) {
newBoard.push(new Array(n + 2).fill(0));
}
for (var i = 1; i < m + 1; i++) {
for (var j = 1; j < n + 1; j++) {
newBoard[i][j] = board[i - 1][j - 1];
}
}
for (var i = 1; i < m + 1; i++) {
for (var j = 1; j < n + 1; j++) {
var lives =
newBoard[i - 1][j - 1] +
newBoard[i - 1][j] +
newBoard[i - 1][j + 1] +
newBoard[i][j - 1] +
newBoard[i][j + 1] +
newBoard[i + 1][j - 1] +
newBoard[i + 1][j] +
newBoard[i + 1][j + 1];
if (newBoard[i][j] === 1) {
if (lives === 2 || lives === 3) {
board[i - 1][j - 1] = 1;
} else {
board[i - 1][j - 1] = 0;
}
} else {
if (lives === 3) {
board[i - 1][j - 1] = 1;
} else {
board[i - 1][j - 1] = 0;
}
}
}
}
return board;
};
console.log(
gameOfLife([
[0, 1, 0],
[0, 0, 1],
[1, 1, 1],
[0, 0, 0],
])
);