Quellcode durchsuchen

Add day 2 part 1 solution

ApisNecros vor 2 Wochen
Ursprung
Commit
fa55367d3b
2 geänderte Dateien mit 79 neuen und 0 gelöschten Zeilen
  1. 73 0
      2/2_1.js
  2. 6 0
      2/test.input

+ 73 - 0
2/2_1.js

@@ -0,0 +1,73 @@
+import { loadInput, numericAscSort, strToInt } from "../common.js";
+
+// const input = loadInput("./2/test.input", parseInput, true);
+const input = loadInput(2, parseInput);
+
+solve(input);
+
+/**
+ * @param {string} inputData
+ * @returns {number[]}
+ */
+function parseInput(inputData) {
+    const reports = inputData.split(/\n/).map((report) => report.split(" ").map(strToInt));
+
+    return reports;
+}
+
+/**
+ * @param {number[]} parsedInput 
+ */
+function solve(parsedInput) {
+    let safeReports = 0;
+
+    for(const report of parsedInput) {
+        let currDirection = 0;
+        let lastDirection = 0;
+        /**
+         * Whether or not the report is safe
+         * 
+         * Report is only safe when the data is sorted in one direction, and
+         * each value is no less than 1 value away, and no more than 3 values
+         * away from each other.
+         *
+         * e.g.
+         * ```
+         * 1,2,3,4,5    safe
+         * 5,4,3,2,1    safe
+         * 1,2,3,2,1    unsafe
+         * 1,2,4,5,6    safe
+         * 1,2,7,8,9    unsafe
+         * ```
+         */
+        let safe = false;
+
+        // Safety check written this way to make troubleshooting easier
+        for(let i = 0; i < report.length - 1; i++) {
+            currDirection = numericAscSort(report[i], report[i + 1]);
+            const difference = Math.abs(report[i] - report[i + 1]);
+
+            // Check if the direction has changed, but skip the first round
+            // Also catches if there were no differences between the two numbers
+            if(i != 0 && lastDirection != currDirection) {
+                safe = false;
+                break;
+            }
+            // Make sure the difference wasn't too great
+            else if(difference > 3) {
+                safe = false;
+                break;
+            }
+            else {
+                safe = true;
+            }
+
+            lastDirection = currDirection;
+        }
+
+        if(safe) { safeReports++; }
+    }
+
+    // Not: ^400, ^391
+    console.log("Safe Reports:", safeReports);
+}

+ 6 - 0
2/test.input

@@ -0,0 +1,6 @@
+7 6 4 2 1
+1 2 7 8 9
+9 7 6 2 1
+1 3 2 4 5
+8 6 4 4 1
+1 3 6 7 9