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)) +);