-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
44 lines (34 loc) · 965 Bytes
/
index.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
export function part1(input: string) {
let safe = 0
for (const report of lines(input)) {
const levels = numbers(report)
if (isSafe(levels))
safe++
}
return safe
}
function isSafe(levels: number[]): boolean {
const differences = levels.slice(1).map((n, i) => n - levels[i])
const allIncreasing = differences.every(d => d > 0)
const allDecreasing = differences.every(d => d < 0)
const validDifferences = differences.every(d => Math.abs(d) >= 1 && Math.abs(d) <= 3)
return (allIncreasing || allDecreasing) && validDifferences
}
export function part2(input: string) {
let safe = 0
for (const report of lines(input)) {
const levels = numbers(report)
if (isSafe(levels)) {
safe++
continue
}
for (let i = 0; i < levels.length; i++) {
const filtered = [...levels.slice(0, i), ...levels.slice(i + 1)]
if (isSafe(filtered)) {
safe++
break
}
}
}
return safe
}