diff options
Diffstat (limited to 'day-9/script.ts')
-rw-r--r-- | day-9/script.ts | 26 |
1 files changed, 26 insertions, 0 deletions
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 }); |