-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday02.ts
60 lines (52 loc) · 1.23 KB
/
day02.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
import type { Day } from './Day.ts';
export class DayImpl implements Day {
private readonly input: Array<Array<number>>;
constructor(input: string) {
this.input = this.parseInput(input);
}
parseInput(input: string) {
return input
.trim()
.split('\n')
.map((line: string) => {
return line
.split(/\s+/)
.map(e => Number.parseInt(e, 10));
});
}
partOne() {
return this.input.map(checkReport).filter(Boolean).length;
}
partTwo() {
return this.input.map(checkReportWithDampener).filter(Boolean).length;
}
}
function checkReport(line: number[]) {
const order = line[0] - line[1];
for (let i = 0; i < line.length - 1; i++) {
const diff = line[i] - line[i + 1];
if (order === 0) {
return false;
}
if (order > 0 && (diff > 3 || diff < 1)) {
return false;
}
if (order < 0 && (diff < -3 || diff > -1)) {
return false;
}
}
return true;
}
function checkReportWithDampener(line: number[]) {
if (checkReport(line)) {
return true;
}
for (let i = 0; i < line.length; i++) {
const clone = [...line];
delete clone[i];
if (checkReport(clone.filter(Number))) {
return true;
}
}
return false;
}