-
Notifications
You must be signed in to change notification settings - Fork 0
/
b.test.ts
92 lines (81 loc) · 1.96 KB
/
b.test.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
91
92
import { expect, test } from "bun:test";
interface DigitMap {
[key: string]: number;
}
const digit: DigitMap = {
one: 1,
two: 2,
three: 3,
four: 4,
five: 5,
six: 6,
seven: 7,
eight: 8,
nine: 9,
};
const startsWith = (str: string, pos: number): number | null => {
for (const key in digit) {
if (str.startsWith(key, pos)) {
return digit[key];
}
}
return null;
};
const endsWith = (str: string, pos: number): number | null => {
for (const key in digit) {
if (str.endsWith(key, pos)) {
return digit[key];
}
}
return null;
};
function solution(input: string) {
const lines = input.split("\n");
const ans = lines.reduce((acc, line) => {
let i = 0;
let j = line.length - 1;
let d = "";
while (i < line.length) {
const symb = line[i];
const num = startsWith(line, i);
if (symb >= "0" && symb <= "9") {
d += symb;
break;
}
if (num) {
d += num;
break;
}
i++;
}
while (j > -1) {
const symb = line[j];
const num = endsWith(line, j + 1);
if (symb >= "0" && symb <= "9") {
d += symb;
break;
}
if (num) {
d += num;
break;
}
j--;
}
return acc + Number(d);
}, 0);
return ans;
}
test("example-b", async () => {
const file = Bun.file("./01/example-b.txt");
const input = await file.text();
const actual = solution(input);
const expected = 281;
expect(actual).toBe(expected);
});
test("puzzle input", async () => {
const file = Bun.file("./01/input.txt");
const input = await file.text();
const actual = solution(input);
const expected = 54249;
expect(actual).toBe(expected);
});