From 0f20a09f6f503f2e57ce6086301dd20fd4d1d1dc Mon Sep 17 00:00:00 2001 From: David Ashby Date: Mon, 2 Dec 2024 22:58:24 -0500 Subject: [PATCH] ugh day 2 part 2 sucked --- 02/index.ts | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 02/index.ts diff --git a/02/index.ts b/02/index.ts new file mode 100644 index 0000000..ca6258f --- /dev/null +++ b/02/index.ts @@ -0,0 +1,66 @@ +import fs from "node:fs"; + +const data = fs.readFileSync("./inputs/input", "utf8"); + +type runner = { ok: boolean; prev: number; inc: boolean; dec: boolean }; + +const testFunc = (running: runner, current: number, i: number) => { + if (i === 0) { + return { ok: true, prev: current, inc: false, dec: false }; + } + if (!running.ok) { + // quick exit + return running; + } + const diff = Math.abs(running.prev - current); + return { + ok: diff > 0 && diff < 4, + prev: current, + inc: running.inc || running.prev - current > 0, + dec: running.dec || running.prev - current < 0, + }; +}; + +const permute = (report: number[]): number[][] => { + const result: Array> = Array.from( + { length: report.length }, + () => [] + ); + return result.map((_, i) => { + return [...report.slice(0, i), ...report.slice(i + 1)]; + }); +}; + +console.log( + "part one:", + data + .split("\n") + .slice(0, -1) // remove empty trailing newline + .map((v) => v.split(" ").map((c) => parseInt(c, 10))) + .reduce((total, current) => { + const tmp = current.reduce(testFunc, {} as runner); + return (tmp.inc && tmp.dec) || !tmp.ok ? total : total + 1; + }, 0) +); + +console.log( + "part two:", + data + .split("\n") + .slice(0, -1) // remove empty trailing newline + .map((v) => v.split(" ").map((c) => parseInt(c, 10))) + .reduce((total, current) => { + const tmp = current.reduce(testFunc, {} as runner); + // ok, that was fine. + if (tmp.ok && !(tmp.inc && tmp.dec)) { + return total + 1; + } + // otherwise, brute force! + const tmp2 = permute(current) + .map((v) => v.reduce(testFunc, {} as runner)) + .reduce((coll, curr) => { + return coll || (curr.ok && !(curr.inc && curr.dec)); + }, false); + return tmp2 ? total + 1 : total; + }, 0) +);