From 13667f414bb13dfe265bb93003475e8654a04739 Mon Sep 17 00:00:00 2001 From: David Ashby Date: Fri, 6 Dec 2024 13:51:12 -0700 Subject: [PATCH] saw part 2 coming so it was indeed straightforward --- 05/index.ts | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 05/index.ts diff --git a/05/index.ts b/05/index.ts new file mode 100644 index 0000000..7b592c5 --- /dev/null +++ b/05/index.ts @@ -0,0 +1,91 @@ +import fs from "node:fs"; +import { printTime, now } from "../util"; + +const test = false; + +const data = fs.readFileSync( + test ? "./inputs/testinput" : "./inputs/input", + "utf8" +); + +let timer = now.instant(); +console.log( + "part one:", + (() => { + const { ordering, manuals } = data + .split("\n") + .slice(0, -1) + .reduce( + (coll, curr) => { + if (curr === "") { + return coll; + } + if (curr[2] === "|") { + return { ...coll, ordering: [...coll.ordering, curr.split("|")] }; + } + if (curr[2] === ",") { + return { ...coll, manuals: [...coll.manuals, curr.split(",")] }; + } + return coll; + }, + { ordering: [], manuals: [] } as { + ordering: Array>; + manuals: Array>; + } + ); + + return manuals.reduce((coll, curr) => { + const sorted = [...curr].sort((a, b) => { + return ordering.filter((v) => v[0] === a && v[1] === b).length === 0 + ? 1 + : -1; + }); + if (sorted.join(",") === curr.join(",")) { + return coll + parseInt(curr[Math.floor(curr.length / 2)], 10); + } + return coll; + }, 0); + })(), + printTime(now.instant().since(timer)) +); + +timer = now.instant(); +console.log( + "part two:", + (() => { + const { ordering, manuals } = data + .split("\n") + .slice(0, -1) + .reduce( + (coll, curr) => { + if (curr === "") { + return coll; + } + if (curr[2] === "|") { + return { ...coll, ordering: [...coll.ordering, curr.split("|")] }; + } + if (curr[2] === ",") { + return { ...coll, manuals: [...coll.manuals, curr.split(",")] }; + } + return coll; + }, + { ordering: [], manuals: [] } as { + ordering: Array>; + manuals: Array>; + } + ); + + return manuals.reduce((coll, curr) => { + const sorted = [...curr].sort((a, b) => { + return ordering.filter((v) => v[0] === a && v[1] === b).length === 0 + ? 1 + : -1; + }); + if (sorted.join(",") !== curr.join(",")) { + return coll + parseInt(sorted[Math.floor(curr.length / 2)], 10); + } + return coll; + }, 0); + })(), + printTime(now.instant().since(timer)) +);