From c6b560502221d8c3d1e64095785846eec1d93224 Mon Sep 17 00:00:00 2001 From: David Ashby Date: Fri, 13 Dec 2024 00:21:21 -0500 Subject: [PATCH] there's an off-by-one error in here somewhere --- 09/index.ts | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ util.ts | 4 ++++ 2 files changed, 54 insertions(+) create mode 100644 09/index.ts diff --git a/09/index.ts b/09/index.ts new file mode 100644 index 0000000..fc3b35f --- /dev/null +++ b/09/index.ts @@ -0,0 +1,50 @@ +import fs from "node:fs"; +import { printTime, now, toNum } from "../util"; + +const test = true; + +const data = fs.readFileSync( + test ? "./inputs/testinput" : "./inputs/input", + "utf8" +); + +let timer = now.instant(); +console.log( + "part one:", + data + .split("\n") + .slice(0, -1)[0] + .split("") + .map(toNum) + .reduce((disk, curr, index) => { + const fill = index % 2 === 0 ? index / 2 : -1; // -1 represents free space + return [...disk, ...Array.from({ length: curr }, () => fill)]; + }, [] as Array) + .reduce((disk, current, i, a) => { + console.log(disk, current, i, a); + if (current === -1) { + while (true) { + let tail = a.pop(); + if (tail === -1 || tail === undefined) { + continue; + } else { + return [...disk, tail]; + } + } + } else { + return [...disk, current]; + } + }, [] as Array) + .reduce((checksum, curr, i) => { + console.log(curr, i); + return checksum + curr * i; + }, 0), + printTime(now.instant().since(timer)) +); + +// timer = now.instant(); +// console.log( +// "part two:", +// data.split("\n").slice(0, -1), +// printTime(now.instant().since(timer)) +// ); diff --git a/util.ts b/util.ts index b6c25fa..7809709 100644 --- a/util.ts +++ b/util.ts @@ -17,3 +17,7 @@ export const printTime = (duration: Temporal.Duration): string => { return parts.join(", "); }; + +export const toNum = (v: string) => { + return parseInt(v, 10); +};