-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday2.ts
57 lines (49 loc) · 1.25 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
53
54
55
56
57
import { parseInput } from "../utils/inputParser";
export const solvePart1 = (input: string): number => {
const lines = parseInput(input);
let safeCount = 0;
for (const line of lines) {
const nums = line.split(" ").map((val) => Number(val));
if (isArrayValid(nums)) {
safeCount += 1;
}
}
return safeCount;
};
export const solvePart2 = (input: string): number => {
const lines = parseInput(input);
let safeCount = 0;
for (const line of lines) {
const nums = line.split(" ").map((val) => Number(val));
if (isArrayValid(nums)) {
safeCount += 1;
} else {
for (let i = 0; i < nums.length; i++) {
if (isArrayValid(nums.slice(0, i).concat(nums.slice(i + 1)))) {
safeCount += 1;
break;
}
}
}
}
return safeCount;
};
const isArrayValid = (nums: number[]): boolean => {
let isAsc = true;
let prevValue = nums[0];
for (let i = 1; i < nums.length; i++) {
if (Math.abs(nums[i] - prevValue) > 3 || nums[i] === prevValue) {
return false;
}
if (i === 1) {
isAsc = nums[i] - prevValue > 0;
prevValue = nums[i];
continue;
}
if (nums[i] - prevValue > 0 !== isAsc) {
return false;
}
prevValue = nums[i];
}
return true;
};