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