Public
Edited
Sep 17, 2023
Insert cell
Insert cell
Insert cell
function parse(input) {
const rules = new Map();
input.rules.forEach((r) => rules.set(...r.split(" -> ")));
return rules;
}
Insert cell
Insert cell
Insert cell
function pairFreqs(input, numIterations) {
const rules = parse(input);
const pairs = d3.pairs(input.template, (a, b) => a + b);
let freqsPrev = pairs.reduce((e, v) => AOC.addToFreqTable(e, v), new Map());

for (let i = 0; i < numIterations; i++) {
const freqs = new Map();
for (const [pair, f] of freqsPrev.entries()) {
const [a, b] = pair.split("");
const c = rules.get(pair);
[a + c, c + b].forEach((p) => AOC.addToFreqTable(freqs, p, f));
}
freqsPrev = freqs;
}
return freqsPrev;
}
Insert cell
Insert cell
function freqOf(elem, freqs, input) {
return (
(elem === input.template[input.template.length - 1] ? 1 : 0) +
[...freqs.entries()].reduce(
(total, [pair, f]) => (pair.split("")[0] === elem ? total + f : total),
0
)
);
}
Insert cell
Insert cell
function calcRange(input, numIterations) {
const pairTable = pairFreqs(input, numIterations);
const elemFreqs = [...new Set(parse(input).values())].map((elem) =>
freqOf(elem, pairTable, input)
);
return Math.max(...elemFreqs) - Math.min(...elemFreqs);
}
Insert cell
function part1(input) {
return calcRange(input, 10);
}
Insert cell
Insert cell
Insert cell
Insert cell
function part2(input) {
return calcRange(input, 40);
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
test1 = ({ template: test1a, rules: test1b })
Insert cell
test1a = `NNCB`.split("")
Insert cell
Insert cell
puzzleInput = ({ template: puzzleInputA, rules: puzzleInputB })
Insert cell
puzzleInputA = `OHFNNCKCVOBHSSHONBNF`.split("")
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more