-
Notifications
You must be signed in to change notification settings - Fork 0
/
solver.ts
90 lines (81 loc) · 2.27 KB
/
solver.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { PuzzleSolver } from "../types/puzzle-solver.ts";
export default class Solver23D1 implements PuzzleSolver {
private inputLines: string[] = [];
parseInput(input: string[]) {
this.inputLines = input.filter((line) => !!line);
}
solvePart1() {
const sum = this.inputLines.reduce((acc, line) => {
const digits = line
.split("")
.filter((char) =>
["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"].includes(
char
)
);
if (digits.length === 0) {
return acc;
}
const digit1 = digits[0];
const digit2 = digits.reverse()[0];
const calibrationNumber = parseInt(digit1 + digit2, 10);
return acc + calibrationNumber;
}, 0);
return sum;
}
solvePart2() {
const sum = this.inputLines.reduce(
(acc, line) => acc + getCalibrationNumber(line),
0
);
return sum;
}
}
function getCalibrationNumber(inputLine: string): number {
const first = getFirstDigit(inputLine);
const last = getLastDigit(inputLine);
const number = parseInt(first + last, 10);
return isNaN(number) ? 0 : number;
}
function getFirstDigit(inputLine: string): string {
for (let i = 0; i < inputLine.length; i++) {
for (let j = i + 1; j <= inputLine.length; j++) {
const substring = inputLine.substring(i, j);
if (DIGIT_LOOKUP[substring]) {
return DIGIT_LOOKUP[substring];
}
}
}
return "";
}
function getLastDigit(inputLine: string): string {
for (let i = inputLine.length; i >= 0; i--) {
for (let j = i - 1; j >= 0; j--) {
const substring = inputLine.substring(j, i);
if (DIGIT_LOOKUP[substring]) {
return DIGIT_LOOKUP[substring];
}
}
}
return "";
}
const DIGIT_LOOKUP: Record<string, string> = {
one: "1",
two: "2",
three: "3",
four: "4",
five: "5",
six: "6",
seven: "7",
eight: "8",
nine: "9",
"1": "1",
"2": "2",
"3": "3",
"4": "4",
"5": "5",
"6": "6",
"7": "7",
"8": "8",
"9": "9",
};