-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday2.ts
52 lines (47 loc) · 1.09 KB
/
day2.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
import { type MainArgs, parseFile } from './lib/utils.ts';
type Parsed = number[][];
function isSafe(levels: number[]): boolean {
if (levels.length < 2) {
return true;
}
let prev = levels[0];
const dir = Math.sign(prev - levels[1]);
for (let i = 1; i < levels.length; i++) {
const l = levels[i];
const diff = prev - l;
if ((diff === 0) || (Math.abs(diff) > 3) || (Math.sign(diff) !== dir)) {
return false;
}
prev = l;
}
return true;
}
function part1(inp: Parsed): number {
let count = 0;
for (const levels of inp) {
if (isSafe(levels)) {
count++;
}
}
return count;
}
function part2(inp: Parsed): number {
let count = 0;
for (const levels of inp) {
if (isSafe(levels)) {
count++;
} else {
for (let i = 0; i < levels.length; i++) {
if (isSafe(levels.toSpliced(i, 1))) {
count++;
break;
}
}
}
}
return count;
}
export default async function main(args: MainArgs): Promise<[number, number]> {
const inp = await parseFile<Parsed>(args);
return [part1(inp), part2(inp)];
}