-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1.mjs
More file actions
50 lines (43 loc) · 1.03 KB
/
Copy path1.mjs
File metadata and controls
50 lines (43 loc) · 1.03 KB
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
import { readInput } from "./utils.mjs";
const input = readInput(import.meta);
const lettersToDigits = {
one: 1,
two: 2,
three: 3,
four: 4,
five: 5,
six: 6,
seven: 7,
eight: 8,
nine: 9,
};
const addNumbers = (numbersPerLine) =>
numbersPerLine.reduce(
(acc, numbers) => acc + Number(numbers.at(0) + numbers.at(-1)),
0,
);
const solve1 = (input) =>
addNumbers(input.split("\n").map((line) => [...line.match(/\d/g)]));
const solve2 = (input) => {
const numbersPerLine = input
.split("\n")
.map((line) =>
[
...line.matchAll(
new RegExp(
`(?=(\\d|${Object.keys(lettersToDigits).join("|")}))`,
"g",
),
),
]
.map((matchAllResult) => matchAllResult.at(1))
.map((numberOrLetters) =>
numberOrLetters in lettersToDigits
? String(lettersToDigits[numberOrLetters])
: numberOrLetters,
),
);
return addNumbers(numbersPerLine);
};
console.log(solve1(input));
console.log(solve2(input));