February 21, 2024
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
// #folder:aoc2023
// @aoc2023
// @title Day 1 solutions
import getAocData from "https://esm.town/v/nbbaier/getAocData";
const data = await getAocData(1);
const input = (await data.text()).split("\n").slice(0, -1);
const numberMap: Map<string, number> = new Map<string, number>([
["one", 1],
["two", 2],
["three", 3],
["four", 4],
["five", 5],
["six", 6],
["seven", 7],
["eight", 8],
["nine", 9],
]);
function findDigits(line: string) {
const foundDigits = Array.from(numberMap.entries()).map((number) => ({
matches: Array.from(
line.matchAll(new RegExp(`${number[0]}|${number[1]}`, "g")),
),
}));
return foundDigits;
}
export const solution = (() => {
const partOne = input
.map(line => Array.from(line).filter(char => /\d/.test(char)))
.map(line => line.length > 1 ? line[0] + line[line.length - 1] : line[0] + line[0])
.map(num => parseInt(num)).reduce((total, num) => total + num, 0);
const partTwo = input.map(line =>
findDigits(line)
.flatMap(el => el.matches.map((match) => ({ digit: match[0], index: match.index })))
.sort((a, b) => a.index - b.index)
.map((element) => /\d/.test(element.digit) ? Number(element.digit) : numberMap.get(element.digit))
)
.map(line => line.length > 1 ? `${line[0]}${line[line.length - 1]}` : `${line[0]}${line[0]}`)
.map(num => parseInt(num))
.reduce((total, num) => total + num, 0);
return { partOne, partTwo };
})();
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
February 21, 2024