-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbacteria.mjs
68 lines (55 loc) · 1.63 KB
/
bacteria.mjs
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
import * as readline from "node:readline";
import { argv, stdin as input, stdout as output } from "node:process";
import { Record, Set } from "immutable";
export const Cell = Record({ x: 0, y: 0 });
export function parseInput() {
const generations = parseInt(argv[2], 10) || 1;
const cells = [];
return new Promise((resolve, reject) => {
const rl = readline.createInterface({ input, output });
rl.write("Please enter the location of the live cells\n");
rl.prompt();
rl.on("line", (line) => {
const [x, y] = line.split(",").map((n) => parseInt(n, 10));
if (x === -1 && y === -1) {
rl.close();
} else {
cells.push(Cell({ x, y }));
rl.prompt();
}
});
rl.on("close", () => {
resolve([Set(cells), generations]);
});
});
}
export function getNeighbours({ x, y }) {
const neighbours = [
[x - 1, y - 1],
[x, y - 1],
[x + 1, y - 1],
[x - 1, y],
[x + 1, y],
[x - 1, y + 1],
[x, y + 1],
[x + 1, y + 1],
].map(([nX, nY]) => Cell({ x: nX, y: nY }));
return Set(neighbours);
}
export function calculateNextGeneration(cells) {
const cellsWithNeighbours = cells.union(
cells.flatMap((c) => getNeighbours(c))
);
return cellsWithNeighbours.filter((c) => {
const isAlive = cells.has(c);
const aliveNeighbours = getNeighbours(c).filter((n) => cells.has(n)).size;
return (
(isAlive && (aliveNeighbours === 2 || aliveNeighbours === 3)) ||
(!isAlive && aliveNeighbours === 3)
);
});
}
export function printCells(cells) {
console.log("\nResult:");
cells.sort().forEach(({ x, y }) => console.log(`${x},${y}`));
}