summaryrefslogtreecommitdiff
path: root/day-9/script.ts
blob: 150c26d9f6ea214cc04fcbe55ac9cac29c334ae0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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).reverse())
  .map(predictValue)
  .reduce((sum, value) => sum + value, 0);

console.log({ result });