-
Notifications
You must be signed in to change notification settings - Fork 0
/
part2.js
69 lines (59 loc) · 1.43 KB
/
part2.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const { readFileSync } = require("fs");
// Parse Input
const inputFile = "input.txt";
let reports = [];
const input = readFileSync(inputFile).toString();
input.split("\n").forEach((line) => {
if (line.split(" ").length > 1) {
reports.push(line.split(" ").map((x) => parseInt(x)));
}
});
function checkReport(r) {
let current = r[0];
let gap = 0;
let valid = true;
r.slice(1).forEach((x) => {
if (valid == false) return;
if (gap == 0) {
if (current + 1 == x || current + 2 == x || current + 3 == x) {
gap = 1;
current = x;
} else if (current - 1 == x || current - 2 == x || current - 3 == x) {
gap = -1;
current = x;
} else {
valid = false;
}
} else if (gap > 0) {
if (current + 1 == x || current + 2 == x || current + 3 == x) {
current = x;
} else {
valid = false;
}
} else {
if (current - 1 == x || current - 2 == x || current - 3 == x) {
current = x;
} else {
valid = false;
}
}
});
return valid;
}
function removeElementAtIndex(arr, index) {
let newArray = [...arr];
newArray.splice(index, 1);
return newArray;
}
// Compute Safe reports
let result = 0;
reports.forEach((r) => {
let valid = checkReport(r);
for (let i = 0; i < r.length; i++) {
if (!valid) {
valid = checkReport(removeElementAtIndex(r, i));
}
}
if (valid) result++;
});
console.log(result);