51 lines
1.0 KiB
JavaScript
Raw Permalink Normal View History

2024-12-02 10:50:22 +01:00
const fs = require("fs");
const file = "inputs/2";
const fileContent = fs.readFileSync(file, "utf-8").trim();
const reports = fileContent.split("\n");
let safeCount = 0;
function isSafe(numbers) {
const isIncreasing = numbers.every(
(num, i) => i === 0 || num > numbers[i - 1]
);
const isDecreasing = numbers.every(
(num, i) => i === 0 || num < numbers[i - 1]
);
const isValidJumps = numbers.every(
(num, i) => i === 0 || Math.abs(num - numbers[i - 1]) <= 3
);
return (isIncreasing || isDecreasing) && isValidJumps;
}
for (const element of reports) {
const arr = element.trim().split(" ");
const numbers = arr.map(Number);
if (isSafe(numbers)) {
safeCount += 1;
continue;
}
let isSafeAfterRemoval = false;
for (let i = 0; i < numbers.length; i++) {
const newNumbers = numbers.slice(0, i).concat(numbers.slice(i + 1));
if (isSafe(newNumbers)) {
isSafeAfterRemoval = true;
break;
}
}
if (isSafeAfterRemoval) {
safeCount += 1;
}
}
console.log(safeCount);