curriculum/challenges/english/blocks/daily-coding-challenges-javascript/691b559495c5cb5a37b9b485.md
Given a matrix (array of arrays) representing the current state in Conway's Game of Life, return the next state of the matrix using these rules:
1 (alive) or 0 (dead).Rules for updating each cell:
For example, given:
[
[0, 1, 0],
[0, 1, 1],
[1, 1, 0]
]
return:
[
[0, 1, 1],
[0, 0, 1],
[1, 1, 1]
]
Each cell updates according to the number of live neighbors. For instance, [0][0] stays dead (2 live neighbors), [0][1] stays alive (2 live neighbors), [0][2] dies (3 live neighbors), and so on.
gameOfLife([[0, 1, 0], [0, 1, 1], [1, 1, 0]]) should return [[0, 1, 1], [0, 0, 1], [1, 1, 1]].
assert.deepEqual(gameOfLife([[0, 1, 0], [0, 1, 1], [1, 1, 0]]), [[0, 1, 1], [0, 0, 1], [1, 1, 1]]);
gameOfLife([[1, 1, 0, 0], [1, 0, 1, 0], [0, 1, 1, 1], [0, 0, 1, 0]]) should return [[1, 1, 0, 0], [1, 0, 0, 1], [0, 0, 0, 1], [0, 1, 1, 1]].
assert.deepEqual(gameOfLife([[1, 1, 0, 0], [1, 0, 1, 0], [0, 1, 1, 1], [0, 0, 1, 0]]), [[1, 1, 0, 0], [1, 0, 0, 1], [0, 0, 0, 1], [0, 1, 1, 1]]);
gameOfLife([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) should return [[0, 0, 0], [0, 1, 0], [0, 0, 0]].
assert.deepEqual(gameOfLife([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), [[0, 0, 0], [0, 1, 0], [0, 0, 0]]);
gameOfLife([[0, 1, 1, 0], [1, 1, 0, 1], [0, 1, 1, 0], [0, 0, 1, 0]]) should return [[1, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]].
assert.deepEqual(gameOfLife([[0, 1, 1, 0], [1, 1, 0, 1], [0, 1, 1, 0], [0, 0, 1, 0]]), [[1, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]]);
function gameOfLife(grid) {
return grid;
}
function gameOfLife(grid) {
const rows = grid.length;
const cols = grid[0].length;
const countLiveNeighbors = (r, c) => {
let count = 0;
for (let i = r - 1; i <= r + 1; i++) {
for (let j = c - 1; j <= c + 1; j++) {
if (
i >= 0 &&
i < rows &&
j >= 0 &&
j < cols &&
!(i === r && j === c) &&
grid[i][j] === 1
) {
count++;
}
}
}
return count;
};
const next = grid.map(row => [...row]);
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const liveNeighbors = countLiveNeighbors(r, c);
if (grid[r][c] === 1) {
if (liveNeighbors < 2 || liveNeighbors > 3) next[r][c] = 0;
} else {
if (liveNeighbors === 3) next[r][c] = 1;
}
}
}
return next;
}