-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
73 lines (63 loc) · 1.93 KB
/
index.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
import { readFile } from 'fs/promises';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const input = await readFile(join(__dirname, './input.txt'), 'utf8');
// #region Part One
const getPartOneAnswer = (input: string) => {
const lines = input.split('\n');
const lineNumbers = lines
.map((line) => (line.match(/\d/g) || []).map(Number))
.filter((numbers) => numbers.length && numbers.every(Number));
const sum = lineNumbers.reduce((acc, numbers) => {
const first = numbers[0];
const last = numbers[numbers.length - 1];
acc += Number([first, last].join(''));
return acc;
}, 0);
return sum;
};
console.log('Part 1 answer:', getPartOneAnswer(input));
// #endregion
// #region Part Two
const numberStrings = {
one: 1,
two: 2,
three: 3,
four: 4,
five: 5,
six: 6,
seven: 7,
eight: 8,
nine: 9,
};
const getPartTwoAnswer = (input: string) => {
const lines = input.split('\n');
const lineNumbers = lines
.map((line) => {
const numberMatches = [];
numberMatches.push(...Array.from(line.matchAll(/\d/g)));
for (const numberString in numberStrings) {
const _matches = Array.from(line.matchAll(new RegExp(numberString, 'g')));
for (const match of _matches) {
match[0] = numberStrings[numberString as keyof typeof numberStrings].toString();
numberMatches.push(match);
}
}
return numberMatches
.filter((x): x is typeof x & { index: number } => x.index != null)
.toSorted((a, b) => (a.index > b.index ? 1 : -1))
.map((x) => Number(x[0]));
})
.filter((numbers) => numbers.length && numbers.every(Number));
const sum = lineNumbers.reduce((acc, numbers) => {
const first = numbers[0];
const last = numbers[numbers.length - 1];
acc += Number([first, last].join(''));
return acc;
}, 0);
return sum;
};
console.log('Part 2 answer:', getPartTwoAnswer(input));
// #endregion