From 5cf420dc2650e9a3155699e7be9284b25baee406 Mon Sep 17 00:00:00 2001 From: Baipyrus Date: Sat, 9 Dec 2023 22:31:48 +0100 Subject: [PATCH] init d9p2 --- Day9/Part2.js | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Day9/Part2.js diff --git a/Day9/Part2.js b/Day9/Part2.js new file mode 100644 index 0000000..6782614 --- /dev/null +++ b/Day9/Part2.js @@ -0,0 +1,35 @@ +import { readFileSync } from "fs"; +const t0 = performance.now(); + +const input = readFileSync("input.txt") + .toString() + .split("\n") + .filter((e) => e.length > 0); +const histories = input.map((e) => e.split(" ").map(Number)); +const predictions = histories.map((e) => { + let current = e; + const sequences = []; + while (!current.every((e) => e === 0)) { + sequences.push(current); + current = current.reduce((a, n, i) => { + if (i === 0) return a; + const d = n - current[i - 1]; + const t = a; + t.push(d); + return t; + }, []); + } + const last = sequences.pop(); + const extrapolated = [[...last, last[0]]]; + for (const s of sequences.reverse()) { + const current = s.pop(); + const last = extrapolated.pop().pop(); + extrapolated.push([...s, current + last]); + } + return extrapolated.pop().pop(); +}); +const sum = predictions.reduce((a, i) => a + i); +console.log(sum); + +const t1 = performance.now(); +console.log(`Runtime: ${t1 - t0}ms`);