Browse Source

Add day 9 part ii solution

ApisNecros 1 year ago
parent
commit
b038638d5f
1 changed files with 68 additions and 0 deletions
  1. 68 0
      9/9_2.ts

+ 68 - 0
9/9_2.ts

@@ -0,0 +1,68 @@
+import { SumArray, ArrayIsOnlyDuplicates, LoadInput, Inspect } from "../common.ts";
+import { FindDifferential, ParseInput, type Histogram } from "./9_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;
+    }
+});
+
+Inspect(histograms);
+
+// Sum all of the last values in the histograms
+const sumOfNewValues = SumArray(histograms.map((histogram) => histogram[0]));
+
+console.log(`The sum of all predicted values is: ${sumOfNewValues}`);
+
+/**
+ * Predict the next value in a histogram
+ *
+ * @param histogram The histogram to find the next value for
+ * @returns The input histogram with its new value added
+ */
+function PredictNextValue(histogram: Histogram): Histogram {
+    const allDifferentials = [histogram];
+    let differential = [];
+    
+    // Get all differentials until only an array of zeros remains
+    do {
+        differential = FindDifferential(allDifferentials[0]);
+        allDifferentials.unshift(differential);
+    } while (!ArrayIsOnlyDuplicates(differential));
+
+    console.log(allDifferentials);
+
+    while (allDifferentials.length > 1) {
+        // Store the last value of previous differential, and remove that differential from the list
+        const firstValueOfDifferential = allDifferentials.shift()?.shift() as number;
+        // if (lastValueOfDifferential == undefined) {
+        //     throw new Error("There is no last value of previous differential!\n" + prevDifferential);
+        // }
+        // Predict the next value to be this last value + the last value of the previous differential
+        const predictedValue = allDifferentials[0][0] - firstValueOfDifferential;
+
+        if (Number.isNaN(predictedValue)) {
+            throw new Error("Failed to find differentials for the following histograms!\n" + histogram);
+        }
+
+        // Push to this differential
+        allDifferentials[0].unshift(predictedValue);
+    }
+
+    return allDifferentials[0];
+}