Browse Source

Add day 1 part 2 solution

ApisNecros 3 months ago
parent
commit
1cfcc2f5e2
1 changed files with 65 additions and 0 deletions
  1. 65 0
      1/1_2.js

+ 65 - 0
1/1_2.js

@@ -0,0 +1,65 @@
+import { loadInput } from "../common.js";
+
+/** A dictionary to cache the counts of values from the right dictionary */
+const _countDictionary = {};
+
+// const input = loadInput("./1/test.input", parseInput, true);
+const input = loadInput(1, parseInput);
+
+solve(input);
+
+/**
+ * @param {string} inputData
+ * @returns {number[][]}
+ */
+function parseInput(inputData) {
+    // Split the input into lines, and then split each line into two numbers
+    const lines = inputData.split(/\n/);
+    let leftList = [];
+    let rightList = [];
+
+    // split each line into two numbers, then add those to the left and right lists
+    for(const line of lines) {
+        const [l, r] = line.split(/\s+/).map((num) => parseInt(num, 10));
+        leftList.push(l);
+        rightList.push(r);
+    }
+
+    return [leftList, rightList];
+}
+
+/**
+ * @param {number[][]} parsedInput
+ */
+function solve(parsedInput) {
+    // separate out the already sorted left and right list
+    const [leftList, rightList] = parsedInput;
+    // Create a list to store the differences between the left and right list
+    const similarityValues = [];
+
+    for(const left of leftList) {
+        similarityValues.push(left * countFromRightList(left, rightList));
+    }
+
+    console.log("List Distance: ", eval(similarityValues.join("+")));
+}
+
+/**
+ * Get a count of the number of times a value appears in the right list
+ *
+ * @param {number} numberToFind The number to get a count of
+ * @param {number[]} rightList The list to search through to get a count of {@link numberToFind}
+ *
+ * @returns {number} The number of times {@link numberToFind} appears in the right list
+ */
+function countFromRightList(numberToFind, rightList) {
+    if(_countDictionary[numberToFind]) {
+        return _countDictionary[numberToFind];
+    }
+
+    const count = rightList.filter((value) => value == numberToFind).length;
+
+    _countDictionary[numberToFind] = count;
+
+    return count;
+}