AoC-23/Day09/Part1.js

36 lines
924 B
JavaScript
Raw Normal View History

2023-12-09 18:00:19 +00:00
import { readFileSync } from "fs";
const t0 = performance.now();
const input = readFileSync("input.txt")
.toString()
2023-12-11 09:56:20 +00:00
.split(/\r*\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();
2023-12-09 21:42:38 +00:00
let extrapolated = [...last, last[0]];
for (const s of sequences.reverse()) {
const current = s.pop();
2023-12-09 21:42:38 +00:00
const last = extrapolated.pop();
extrapolated = [...s, current + last];
}
2023-12-09 21:42:38 +00:00
return extrapolated.pop();
});
const sum = predictions.reduce((a, i) => a + i);
console.log(sum);
2023-12-09 18:00:19 +00:00
const t1 = performance.now();
console.log(`Runtime: ${t1 - t0}ms`);