123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- import { ExtractNumbers, Inspect, LoadInput } from "../common.ts";
- const tests = [
- "0 3 6 9 12 15",
- "1 3 6 10 15 21",
- "10 13 16 21 30 45",
- ];
- const input = await LoadInput(9);
- let histograms = ParseInput(input);
- histograms = histograms.map((histogram, idx) => {
- try {
- return PredictNextValue(histogram);
- } catch (err) {
- console.error(`Failed on histogram[${idx}]`);
- throw err;
- }
- });
- const sumOfNewValues = SumArray(histograms.map((histogram) => histogram[histogram.length - 1]));
- console.log(`The sum of all predicted values is: ${sumOfNewValues}`);
- function ParseInput(inputArr: string[]): number[][] {
- return inputArr.map((historyStr) => ExtractNumbers(historyStr));
- }
- function PredictNextValue(histogram: number[]): number[] {
- const allDifferentials = [histogram];
- let differential = [];
-
-
- do {
- differential = FindDifferential(allDifferentials[0]);
- allDifferentials.unshift(differential);
- } while (SumArray(differential) != 0);
- while (allDifferentials.length > 1) {
-
- const lastValueOfDifferential = allDifferentials.shift()?.pop() as number;
-
-
-
-
- const lastIndexOfDifferential = allDifferentials[0].length - 1;
-
-
-
-
- const predictedValue = allDifferentials[0][lastIndexOfDifferential] + lastValueOfDifferential;
- if (Number.isNaN(predictedValue)) {
- throw new Error("Failed to find differentials for the following histograms!\n" + histogram);
- }
-
- allDifferentials[0].push(predictedValue);
- }
- return allDifferentials[0];
- }
- function FindDifferential(histogram: number[]): number[] {
- const differential: number[] = [];
- for (let i = 1; i < histogram.length; i++) {
- differential.push(histogram[i] - histogram[i - 1]);
- }
- return differential;
- }
- function SumArray(arr: number[]): number {
- return arr.reduce((accumulator, value) => accumulator += value, 0);
- }
|