123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- import { deepClone, loadInput, numericAscSort, strToInt } from "../common.js";
- let _;
- const input = loadInput(2, parseInput);
- solve(input);
- function parseInput(inputData) {
- const reports = inputData.split(/\n/).map((report) => report.split(" ").map(strToInt));
- return reports;
- }
- function solve(parsedInput) {
- let safeReports = 0;
- for(const report of parsedInput) {
- let [isSafe, unsafeIndex] = isReportSafe(report);
-
-
- if(!isSafe) {
- console.warn("Report wasn't safe. Checking other variations");
-
- let reportClone = deepClone(report);
-
- reportClone.splice(unsafeIndex, 1);
- console.warn("Trying modified report: ", reportClone);
-
- [isSafe, _] = isReportSafe(reportClone);
-
- if(!isSafe) {
- reportClone = deepClone(report);
- reportClone.splice(unsafeIndex + 1, 1);
- console.warn("Trying modified report: ", reportClone);
- [isSafe, _] = isReportSafe(reportClone);
- }
- console.log();
- }
- if(isSafe) { safeReports++; }
- }
-
- console.log("Safe Reports:", safeReports);
- }
- function isReportSafe(report) {
- let currDirection = 0;
- let lastDirection = 0;
-
- let safe = false;
- let unsafeLevel = null;
-
- 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]);
-
-
- if(i != 0 && lastDirection != currDirection) {
- unsafeLevel = i;
- safe = false;
- break;
- }
-
- else if(difference > 3) {
- unsafeLevel = i;
- safe = false;
- break;
- }
- else {
- safe = true;
- }
- lastDirection = currDirection;
- }
- return [safe, unsafeLevel];
- }
|