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); }