From 4d93fa700fcec059559fe6e16c5f02a297f59925 Mon Sep 17 00:00:00 2001 From: eug-vs Date: Sat, 9 Dec 2023 22:53:31 +0300 Subject: feat(day-9): add first part solution --- day-9/script.ts | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 day-9/script.ts (limited to 'day-9/script.ts') diff --git a/day-9/script.ts b/day-9/script.ts new file mode 100644 index 0000000..cb1ac38 --- /dev/null +++ b/day-9/script.ts @@ -0,0 +1,26 @@ +import fs from "fs"; + +function differences(sequence: number[]) { + return sequence.reduce((acc, value, index) => { + const next = sequence[index + 1]; + if (next !== undefined) acc.push(next - value); + return acc; + }, [] as number[]); +} + +function predictValue(sequence: number[]) { + if (sequence.every((item) => item === 0)) return 0; + const diff = predictValue(differences(sequence)); + return sequence[sequence.length - 1] + diff; +} + +const result = fs + .readFileSync("./input.txt") + .toString() + .split("\n") + .slice(0, -1) + .map((line) => line.split(" ").map(Number)) + .map(predictValue) + .reduce((sum, value) => sum + value, 0); + +console.log({ result }); -- cgit v1.2.3