-
Notifications
You must be signed in to change notification settings - Fork 0
/
day-2.js
53 lines (47 loc) · 1.15 KB
/
day-2.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { readFileSync } from "node:fs";
const inputBuffer = readFileSync("./day-2.txt");
const INCREASING = 1;
const DECREASING = 0;
let safeReports = 0;
inputBuffer
.toString()
.split("\n")
.forEach((reportLine) => {
const report = reportLine.split(" ").map(Number);
if (isSafeReport(report)) return safeReports++;
report.some((_, index) => {
const tentative = report.filter((_, i) => i !== index);
if (isSafeReport(tentative)) {
return ++safeReports;
}
});
});
/**
* @param {number[]} report
*/
function isSafeReport(report) {
let order;
let isSafe = false;
for (let i = 1; i < report.length; i++) {
const diff = Math.abs(report[i] - report[i - 1]);
if (diff < 1 || diff > 3) {
isSafe = false;
break;
}
if (i === 1) {
order = report[i] > report[i - 1] ? INCREASING : DECREASING;
continue;
}
if (report[i] > report[i - 1] && order !== INCREASING) {
isSafe = false;
break;
}
if (report[i] < report[i - 1] && order !== DECREASING) {
isSafe = false;
break;
}
isSafe = true;
}
return isSafe;
}
console.log({ safeReports });