-
Notifications
You must be signed in to change notification settings - Fork 0
/
GameOfLifeNRuns.js
84 lines (69 loc) · 1.93 KB
/
GameOfLifeNRuns.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
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
/*
Any live cell with two or three live neighbours survives.
Any dead cell with three live neighbours becomes a live cell.
All other live cells die in the next generation. Similarly, all other dead cells stay dead.
calculate the state of the board after n iterations
assume the board is a square
*/
const EMPTY = " ";
const LIVE = "X";
function countLiveNeighbors(board, r, c) {
let count = 0;
if (r > 0) {
count += board[r - 1][c] != EMPTY ? 1 : 0;
}
if (c > 0) {
count += board[r][c - 1] != EMPTY ? 1 : 0;
if (r > 0) {
count += board[r - 1][c - 1] != EMPTY ? 1 : 0;
}
if (r < board.length - 2) {
count += board[r + 1][c - 1] != EMPTY ? 1 : 0;
}
}
if (r < board.length - 2) {
count += board[r + 1][c] != EMPTY ? 1 : 0;
}
if (c < board.length - 2) {
count += board[r][c + 1] != EMPTY ? 1 : 0;
if (r < board.length - 2) {
count += board[r + 1][c + 1] != EMPTY ? 1 : 0;
}
if (r > 0) {
count += board[r - 1][c + 1] != EMPTY ? 1 : 0;
}
}
return count;
}
function gameOfLifeNRuns(board, n) {
while (n >= 0) {
const newBoard = [];
for (let r = 0; r < board.length; r++) {
const newRow = [];
for (let c = 0; c < board[r].length; c++) {
const element = board[r][c];
const count = countLiveNeighbors(board, r, c);
if ((element == LIVE && count > 3) || count < 2) {
newRow.push(EMPTY);
} else if (count == 3) {
newRow.push(LIVE);
} else {
newRow.push(element);
}
}
newBoard.push(newRow); // use a new board so changes in current board won't interfere
}
board = newBoard;
n--;
console.log(board);
}
}
const board = [
[" ", " ", " ", " ", " ", " "],
[" ", " ", "X", " ", " ", " "],
["X", " ", "X", " ", " ", " "],
[" ", "X", "X", " ", " ", " "],
[" ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " "],
];
gameOfLifeNRuns(board, 9);