advent-of-code-2023/src/day_nine.ts

44 lines
1.6 KiB
TypeScript

import fs from "fs";
export class Oasis {
private readonly sequences: number[][];
constructor(input: string) {
this.sequences = input.split('\n').map(line => line.split(' ').map(Number));
}
public getNextValueInSequence(seq: number[]): number {
if (new Set(seq).size === 1) return seq[0];
const differences = seq.reduce((acc: number[], curr, i, arr) => {
if (i === 0) return acc;
acc.push(curr - arr[i - 1]);
return acc;
}, []);
return this.getNextValueInSequence(differences) + seq[seq.length - 1];
}
public getPreviousValueInSequence(seq: number[]): number {
if (new Set(seq).size === 1) return seq[0];
const differences = seq.reduce((acc: number[], curr, i, arr) => {
if (i === 0) return acc;
acc.push(curr - arr[i - 1]);
return acc;
}, []);
return seq[0] - this.getPreviousValueInSequence(differences);
}
public getTotalOfNextValuesInSequences(): number {
return this.sequences.reduce((acc, curr) => acc + this.getNextValueInSequence(curr), 0);
}
public getTotalOfPreviousValuesInSequences(): number {
return this.sequences.reduce((acc, curr) => acc + this.getPreviousValueInSequence(curr), 0);
}
}
export const runDayNine = () => {
const input = fs.readFileSync('./inputs/day_nine_input.txt', 'utf-8').trimEnd();
const oasis = new Oasis(input);
console.log(oasis.getTotalOfNextValuesInSequences());
console.log(oasis.getTotalOfPreviousValuesInSequences());
}