Browse Source

Move common functions for day 9 to common file

ApisNecros 1 year ago
parent
commit
136f81767b
2 changed files with 39 additions and 16 deletions
  1. 9 16
      9/9_1.ts
  2. 30 0
      9/9_common.ts

+ 9 - 16
9/9_1.ts

@@ -1,4 +1,5 @@
-import { ArrayIsOnlyDuplicates, ExtractNumbers, Inspect, LoadInput } from "../common.ts";
+import { ArrayIsOnlyDuplicates, LoadInput } from "../common.ts";
+import { FindDifferential, ParseInput, type Histogram } from "./9_common.ts";
 
 const tests = [
     "0 3 6 9 12 15",
@@ -27,11 +28,13 @@ const sumOfNewValues = SumArray(histograms.map((histogram) => histogram[histogra
 // 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[] {
+/**
+ * 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 = [];
     
@@ -66,16 +69,6 @@ function PredictNextValue(histogram: number[]): number[] {
     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);
 }

+ 30 - 0
9/9_common.ts

@@ -0,0 +1,30 @@
+import { ExtractNumbers } from "../common.ts";
+
+/**
+ * Parse the input for day 9
+ *
+ * @param inputArr An array of strings containing numbers
+ * @returns An array of histograms
+ */
+export function ParseInput(inputArr: string[]): Histogram[] {
+    return inputArr.map((historyStr) => ExtractNumbers(historyStr) as Histogram);
+}
+
+/**
+ * Find the difference of values in a histogram
+ *
+ * @param histogram A array of historical values, or another differential
+ * @returns A new histogram containing the difference of values in the input histogram
+ */
+export function FindDifferential(histogram: Histogram): Histogram {
+    const differential: Histogram = [];
+
+    for (let i = 1; i < histogram.length; i++) {
+        differential.push(histogram[i] - histogram[i - 1]);
+    }
+
+    return differential;
+}
+
+/** An array of historical environment values */
+export type Histogram = number[];