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);
- // Parse the histograms from the input
- let histograms = ParseInput(input);
- // Find the next predicted value for each one
- histograms = histograms.map((histogram, idx) => {
- try {
- return PredictNextValue(histogram);
- } catch (err) {
- console.error(`Failed on histogram[${idx}]`);
- throw err;
- }
- });
- // Sum all of the last values in the histograms
- const sumOfNewValues = SumArray(histograms.map((histogram) => histogram[histogram.length - 1]));
- // Wrong Answers
- // 1987402315 -- too high
- 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 = [];
-
- // Get all differentials until only an array of zeros remains
- do {
- differential = FindDifferential(allDifferentials[0]);
- allDifferentials.unshift(differential);
- } while (SumArray(differential) != 0);
- while (allDifferentials.length > 1) {
- // Store the last value of previous differential, and remove that differential from the list
- const lastValueOfDifferential = allDifferentials.shift()?.pop() as number;
- // if (lastValueOfDifferential == undefined) {
- // throw new Error("There is no last value of previous differential!\n" + prevDifferential);
- // }
- // Store the last index of the current differential for easier reading
- const lastIndexOfDifferential = allDifferentials[0].length - 1;
- // if (lastIndexOfDifferential < 0) {
- // throw new Error("There is no last index of the current differential");
- // }
- // Predict the next value to be this last value + the last value of the previous differential
- const predictedValue = allDifferentials[0][lastIndexOfDifferential] + lastValueOfDifferential;
- if (Number.isNaN(predictedValue)) {
- throw new Error("Failed to find differentials for the following histograms!\n" + histogram);
- }
- // Push to this differential
- 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);
- }
|