Skip to content

Commit 2953b4e

Browse files
committed
init commit
0 parents  commit 2953b4e

11 files changed

+1530
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
node_modules

2023/01/code.ts

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import fs from 'fs'
2+
3+
const input = fs.readFileSync('./2023/01/input.txt', 'utf-8')
4+
5+
const textNumbersRegex = new RegExp(['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'].join('|'), 'g')
6+
7+
function part1(input: string) {
8+
const lines = input.split('\r\n')
9+
const allDigitsRegex = /\d/g
10+
const matches = lines
11+
.map((line) => {
12+
const digits = line.match(allDigitsRegex)
13+
if (!digits) return
14+
const first = digits?.[0]
15+
const last = digits?.[digits.length - 1]
16+
return first + last
17+
})
18+
.filter((value) => value)
19+
.reduce((acc, value) => {
20+
const number = parseInt(value || '0')
21+
return acc + number
22+
}, 0)
23+
return matches
24+
}
25+
26+
function part2(input: string) {
27+
// get lines as array
28+
const lines = input.split('\r\n')
29+
30+
// replace text numbers with digits
31+
const parsedLines = lines.map((line) => {
32+
const parsedLine = line.replace(textNumbersRegex, (match) => {
33+
const number = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'].indexOf(match) + 1
34+
return number.toString()
35+
})
36+
return parsedLine
37+
})
38+
39+
// get all digits
40+
const allDigitsRegex = /\d/g
41+
const matches = parsedLines
42+
.map((line) => {
43+
const digits = line.match(allDigitsRegex)
44+
if (!digits) return 0
45+
const first = digits?.[0]
46+
const last = digits?.[digits.length - 1]
47+
return Number(first + last) || 0
48+
})
49+
.filter((value) => value)
50+
.reduce((acc, value) => {
51+
return acc + value
52+
}, 0)
53+
54+
return matches
55+
}
56+
57+
console.log(part2(input))

2023/01/example.txt

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
two1nine
2+
eightwothree
3+
abcone2threexyz
4+
xtwone3four
5+
4nineeightseven2
6+
zoneight234
7+
7pqrstsixteen

0 commit comments

Comments
 (0)