瀏覽代碼

Add beginning of day 2 part 2 solution

ApisNecros 2 周之前
父節點
當前提交
fad1d209d0
共有 1 個文件被更改,包括 87 次插入0 次删除
  1. 87 0
      2/2_2.js

+ 87 - 0
2/2_2.js

@@ -0,0 +1,87 @@
+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;
+        /**
+         * The Problem Dampener allows one failed safety meassure
+         */
+        let problemDampenerActive = true;
+
+        // 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) {
+                if (problemDampenerActive) {
+                    problemDampenerActive = false;
+                }
+                else {
+                    safe = false;
+                    break;
+                }
+            }
+            // Make sure the difference wasn't too great
+            else if(difference > 3) {
+                if (problemDampenerActive) {
+                    problemDampenerActive = false;
+                }
+                else {
+                    safe = false;
+                    break;
+                }
+            }
+            else {
+                safe = true;
+            }
+
+            lastDirection = currDirection;
+        }
+
+        if(safe) { safeReports++; }
+    }
+
+    // Not: ^400, ^391
+    console.log("Safe Reports:", safeReports);
+}