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);
});
}