-
Notifications
You must be signed in to change notification settings - Fork 0
/
day01.ts
100 lines (86 loc) · 2.2 KB
/
day01.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
93
94
95
96
97
98
99
100
import fs from 'fs';
const digitStrings = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
async function part1() {
const input = fs.readFileSync('input/day01.txt');
const rows = input.toString().split('\r\n');
const digits: number[] = [];
rows.forEach((row) => {
const isDigit = new RegExp(/\d/);
let firstDigit = '';
let lastDigit = '';
for (let i = 0; i < row.length; i++) {
if (isDigit.test(row[i])) {
if (!firstDigit) firstDigit = row[i];
lastDigit = row[i];
}
}
digits.push(parseInt(firstDigit + lastDigit));
});
console.log(digits.reduce((acc, cur) => acc + cur, 0));
}
async function part2() {
const input = fs.readFileSync('input/day01.txt');
const rows = input.toString().split('\r\n');
const digits: number[] = [];
rows.forEach((row) => {
const isDigit = new RegExp(/\d/);
const digitIndexMap = new Map<number, string>();
const indexes: number[] = [];
for (let i = 0; i < row.length; i++) {
if (isDigit.test(row[i])) {
digitIndexMap.set(i, row[i]);
indexes.push(i);
} else {
for (const digitString of digitStrings) {
if (row.startsWith(digitString, i)) {
digitIndexMap.set(i, getDigit(digitString));
indexes.push(i);
}
}
}
}
const minIndex = Math.min(...indexes);
const maxIndex = Math.max(...indexes);
const digit = parseInt(digitIndexMap.get(minIndex)! + digitIndexMap.get(maxIndex)!);
digits.push(digit);
});
console.log(digits.reduce((acc, cur) => acc + cur, 0));
}
function getDigit(digitString: string): string {
let digit: string;
switch (digitString) {
case 'one':
digit = '1';
break;
case 'two':
digit = '2';
break;
case 'three':
digit = '3';
break;
case 'four':
digit = '4';
break;
case 'five':
digit = '5';
break;
case 'six':
digit = '6';
break;
case 'seven':
digit = '7';
break;
case 'eight':
digit = '8';
break;
case 'nine':
digit = '9';
break;
default:
digit = '';
break;
}
return digit;
}
// part1();
part2();