diff options
author | eug-vs <eugene@eug-vs.xyz> | 2023-12-09 22:53:31 +0300 |
---|---|---|
committer | eug-vs <eugene@eug-vs.xyz> | 2023-12-09 22:53:31 +0300 |
commit | 4d93fa700fcec059559fe6e16c5f02a297f59925 (patch) | |
tree | 9fe494f02f9a1492fc5127bcc7d875c7a1f065de /day-9/script.ts | |
parent | a26b6e174542edd2f560675cde98898672d5e293 (diff) | |
download | aoc-2023-4d93fa700fcec059559fe6e16c5f02a297f59925.tar.gz |
feat(day-9): add first part solution
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 }); |