-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2.ts
63 lines (50 loc) · 1.48 KB
/
2.ts
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
import * as fs from 'fs';
const getInput = (): number[][] => {
const filePath = "2-input.txt";
const data = fs.readFileSync(filePath, 'utf8');
const lines = data.split("\n");
const reports = lines.map(line => line.split(" ").map(x => parseInt(x)));
return reports;
};
const part1 = () => {
const reports = getInput();
const safeReports = reports.filter((report) => isSafe(report))
return safeReports.length;
}
const isSafe = (report: number[]): boolean => {
let prevNum = report[0];
let direction = (report[1] - report[0]) > 0 ? 1 : -1;
for (const num of report.slice(1)) {
const diff = num - prevNum;
if (diff > 0 && direction !== 1) {
return false;
}
if (diff < 0 && direction !== -1) {
return false;
}
if (Math.abs(diff) < 1 || Math.abs(diff) > 3) {
return false;
}
prevNum = num;
}
return true;
}
const part2 = () => {
const reports = getInput();
const safeReports = reports.filter((report) => {
if (isSafe(report)) {
return true;
}
for (let i=0; i<report.length; i++) {
const reportWithElemRemoved = [...report.slice(0, i), ...report.slice(i+1)];
const tmp = isSafe(reportWithElemRemoved);
if (tmp) {
return true;
}
}
return false;
})
return safeReports.length;
}
console.log(part1());
console.log(part2());