-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day2.js
79 lines (64 loc) · 1.63 KB
/
Day2.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
70
71
72
73
74
75
76
77
78
const fs = require('fs');
//https://adventofcode.com/2024/day/2
fs.readFile('Day2input.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
const reportsString = data.split('\n');
let safeCounter = 0;
reportsString.forEach(line => {
if(isReportSafe(line)){
safeCounter++;
}
else if(canBeSafe(line)){
safeCounter++;
}
});
console.log(safeCounter);
});
function isReportSafe(report){
let levels;
if(typeof(report) === 'string'){
levels = report.split(' ').map(Number);
}
else{
levels = report;
}
if(!isIncreasing(levels) && !isDecreasing(levels)){
return false;
}
for(let i = 0; i < levels.length - 1; i++){
if(Math.abs(levels[i] - levels[i + 1]) < 1 || Math.abs(levels[i] - levels[i + 1]) > 3){
return false;
}
}
return true;
}
function canBeSafe(report){
const levels = report.split(' ').map(Number);
//call isReportSafe on levels, each time with one element removed
for (let i = 0; i < levels.length; i++) {
const newLevels = levels.filter((_, index) => index !== i);
if(isReportSafe(newLevels)){
return true;
}
}
return false;
}
function isIncreasing(level){
for (let i = 0; i < level.length - 1; i++) {
if(level[i] >= level[i + 1]){
return false;
}
}
return true;
}
function isDecreasing(level){
for (let i = 0; i < level.length - 1; i++) {
if(level[i] <= level[i + 1]){
return false;
}
}
return true;
}