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
|
type Grid = number[][];
export function printGrid(grid: Grid): void {
grid.forEach(row => console.log(row.map(cell => cell ? '1' : '0').join(' ')));
console.log('\n');
}
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 simulate(initial: Grid, steps: number): void {
let grid = initial;
for (let i = 0; i < steps; i++) {
printGrid(grid);
grid = step(grid);
}
}
const initial: Grid = [
[0, 1, 0],
[0, 1, 0],
[0, 1, 0]
];
const flyer: Grid = [
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]
];
const toad: Grid = [
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 1, 0, 0, 1, 0],
[0, 1, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0]
];
console.log('Initial:');
simulate(initial, 5);
console.log('Flyer:');
simulate(flyer, 5);
console.log('Toad:');
simulate(toad, 5);
|