-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfourteen.js
More file actions
60 lines (51 loc) · 1.24 KB
/
Copy pathfourteen.js
File metadata and controls
60 lines (51 loc) · 1.24 KB
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
import { readFile } from 'fs/promises';
// 14a
async function init() {
const input = await readFile('fourteen.txt', 'utf8');
const lines = input.split('\n');
let [MOLECULE, blank, ...RULES] = lines;
MOLECULE = [...MOLECULE].reduce((acc, cur, ind) => {
if (ind < MOLECULE.length - 1) {
const seg = `${cur}${MOLECULE[ind + 1]}`;
if (acc[seg]) {
acc[seg]++;
} else {
acc[seg] = 1;
}
}
return acc;
}, {});
RULES = RULES.reduce((acc, rule) => {
let [match, right] = rule.split(' -> ');
acc[match] = [`${match[0]}${right}`, `${right}${match[1]}`];
return acc;
}, {});
for (let i = 0; i < 40; i++) {
const next = {};
for (const [key, value] of Object.entries(MOLECULE)) {
RULES[key].forEach((seg) => {
if (next[seg]) {
next[seg] += value;
} else {
next[seg] = value;
}
});
}
MOLECULE = next;
}
const scores = Object.entries(MOLECULE).reduce(
(acc, cur) => {
const [seg, count] = cur;
const char = seg[1];
if (acc[char]) {
acc[char] += count;
} else {
acc[char] = count;
}
return acc;
},
{ [lines[0][0]]: 1 }
);
console.log(scores);
}
init();