-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.ts
77 lines (60 loc) · 2.74 KB
/
Main.ts
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 RuleArray = [number, number, number, number, number, number, number, number];
function ruleToBinaryArray(ruleNumber: number): RuleArray {
return ruleNumber.toString(2).padStart(8, '0').split('').map(bit => parseInt(bit, 10)) as RuleArray;
}
function calculateCell(pState: string, rule: RuleArray): number {
const ruleMap: Record<string, number> = {
"111": rule[0],
"110": rule[1],
"101": rule[2],
"100": rule[3],
"011": rule[4],
"010": rule[5],
"001": rule[6],
"000": rule[7]
};
return ruleMap[pState];
}
async function runCellularAutomaton(rule: RuleArray, generations: number, initialCells: number[]): Promise<number[][]> {
let cells : number[] = JSON.parse(JSON.stringify(initialCells));
let ca: number[][] = [];
const padding = Array(2).fill(0);
for (let i = 0; i < generations -1; i++) {
const extendedCells = [...padding, ...cells, ...padding];
ca.push(extendedCells);
const nextGeneration: number[] = [];
for (let j = 1; j < extendedCells.length - 1; j++) {
const neighborhood = '' + extendedCells[j - 1] + extendedCells[j] + extendedCells[j + 1];
nextGeneration.push(calculateCell(neighborhood, rule));
}
cells = nextGeneration;
}
ca.push(cells);
return ca;
}
async function readInputsFromFile(filePath: string): Promise<[number, string, number]> {
const text = await Deno.readTextFile(filePath);
const lines = text.split('\n');
const ruleNumber = parseInt(lines[0].trim(), 10);
const initialConditions = lines[1].trim();
const generations = parseInt(lines[2].trim(), 10);
return [ruleNumber, initialConditions, generations];
}
const padCellularAutomaton = (ca: number[][], totalWidth: number): number[][] => ca.map(row => {
const paddingLength = Math.floor((totalWidth - row.length) / 2);
const padding = Array(paddingLength).fill(0);
return [...padding, ...row, ...padding];
});
// Main function to run the program
async function main() {
const [ruleNumber, initialConditions, generations] = await readInputsFromFile('input.txt');
const initialCells = initialConditions.split('').map(bit => parseInt(bit, 10));
const rule = ruleToBinaryArray(ruleNumber);
const ca: number[][] = await runCellularAutomaton(rule, generations, initialCells);
const finalWidth = initialConditions.length + 2 * generations;
const paddedCA = padCellularAutomaton(ca, finalWidth);
const ca_body = paddedCA.map(row => row.join('')).join('\n');
const imageData = `P1\n${finalWidth} ${generations}\n${ca_body}\n`;
await Deno.writeTextFile(`results/r${ruleNumber}_g${generations}_i${initialConditions}_typescript.pbm`, imageData);
}
main();