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
|
export type Grid = number[][];
// FIXME: I'm exporting way more than is necessary to support testing. What if I didn't do that?
export function countNeighbors(grid: Grid, x: number, y: number): number {
const neighborOffsets = [
[-1, -1], [-1, 0], [-1, 1],
[0, -1], [0, 1],
[1, -1], [1, 0], [1, 1]
];
return neighborOffsets.reduce((count, [dx, dy]) => {
const nx = x + dx;
const ny = y + dy;
if (nx >= 0 && ny >= 0 && nx < grid.length && ny < grid[0].length && grid[nx][ny]) {
return count + 1;
}
return count;
}, 0);
}
export function step(grid: Grid): Grid {
return grid.map((row, x) =>
row.map((cell, y) => {
const neighbors = countNeighbors(grid, x, y);
return neighbors === 3 || (neighbors === 2 && cell) ? 1 : 0;
})
);
}
export function printGrid(grid: Grid): void {
grid.forEach(row => console.log(row.map(cell => cell ? '🟢' : '⚪️').join('')));
console.log('\n');
}
export function simulate(initial: Grid, steps: number): void {
let grid = initial;
Array.from({ length: steps }).forEach(() => {
printGrid(grid);
grid = step(grid);
});
}
|