aoc23/01/index.ts
2023-12-01 23:50:21 +01:00

66 lines
No EOL
1.5 KiB
TypeScript

const fs = require('fs').promises;
const input: string = (await fs.readFile('./input.txt')).toString()
// const testInput = `two1nine
// eightwothree
// abcone2threexyz
// xtwone3four
// 4nineeightseven2
// zoneight234
// 7pqrstsixteen`
const patterns: {[id: string]: string} = {
one: '1',
two: '2',
three: '3',
four: '4',
five: '5',
six: '6',
seven: '7',
eight: '8',
nine: '9'
}
console.log("Solution first part: " + partOne(input))
console.log("Solution second part: " + partTwo(input))
function partOne(input: string): string {
let digits = []
for (const line of input.split('\n')) {
let first = undefined
let last = undefined
for (const char of line) {
const digit = parseInt(char)
if (!Number.isNaN(digit)) {
if (first === undefined) {
first = digit
}
last = digit
}
}
digits.push(parseInt(`${first}${last}`))
}
let sum = digits.reduce((acc, item) => {
return acc += item
})
return `${sum}`
}
function partTwo(input: string): string {
let fixedParts: Array<string> = []
for (const line of input.split('\n')) {
let modified = line
for (const pattern of Object.keys(patterns)) {
let count = 0
for (const match of modified.matchAll(new RegExp(pattern, 'g'))) {
let pos = match.index! + count
modified = [modified.slice(0, pos), pattern[0], patterns[pattern], pattern[pattern.length], modified.slice(pos)].join('')
count += 3
}
}
fixedParts.push(modified)
}
return partOne(fixedParts.join('\n'))
}