Skip to content

Instantly share code, notes, and snippets.

@bluepichu
Created December 14, 2021 05:17
Show Gist options
  • Save bluepichu/90342be01d6ec318655a699a0d6b3114 to your computer and use it in GitHub Desktop.
Save bluepichu/90342be01d6ec318655a699a0d6b3114 to your computer and use it in GitHub Desktop.
import { Map } from 'immutable';
import { Advent, arr, int } from "advent";
const { compute, computeCheck } = await Advent({ day: 14 });
compute(async (input) => {
// const data = input.tokens(/,/).map(int);
// const data = input.ints();
const [start, rules] = input.all().split("\n\n");
let ruleMap = Map<string, string>();
for (let rule of rules.split("\n")) {
let [pattern, result] = rule.split(" -> ");
ruleMap = ruleMap.set(pattern, result);
}
console.log(ruleMap.toJSON());
let pat = Map<string, number>();
for (let i = 0; i < start.length - 1; i++) {
pat = pat.update(start[i] + start[i + 1], 0, (v) => v + 1);
}
for (let i = 0; i < 40; i++) {
pat = step(pat, ruleMap);
}
let outMap = Map<string, number>();
outMap = outMap.update(start[0], 0, (v) => v + 1);
outMap = outMap.update(start[start.length - 1], 0, (v) => v + 1);
for (let [k, c] of pat) {
outMap = outMap.update(k[0], 0, (v) => v + c);
outMap = outMap.update(k[1], 0, (v) => v + c);
}
let min = outMap.minBy((v) => v)!;
let max = outMap.maxBy((v) => v)!;
return (max - min) / 2;
}, 2);
function step(pattern: Map<string, number>, rules: Map<string, string>): Map<string, number> {
let out = Map<string, number>();
for (let [key, cnt] of pattern) {
if (rules.has(key)) {
out = out.update(key[0] + rules.get(key)!, 0, (v) => v + cnt);
out = out.update(rules.get(key)! + key[1], 0, (v) => v + cnt);
}
}
return out;
}
// computeCheck(async function* (input) {
// yield 0;
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment