74 lines
1.6 KiB
TypeScript
74 lines
1.6 KiB
TypeScript
import fs from 'fs';
|
|
|
|
const DIGIT_REGEX = new RegExp(/(?=(\d|one|two|three|four|five|six|seven|eight|nine))/g);
|
|
|
|
function parseDigit(digit: string): string {
|
|
switch (digit) {
|
|
case "one": return "1";
|
|
case "two": return "2";
|
|
case "three": return "3";
|
|
case "four": return "4";
|
|
case "five": return "5";
|
|
case "six": return "6";
|
|
case "seven": return "7";
|
|
case "eight": return "8";
|
|
case "nine": return "9";
|
|
default: return digit;
|
|
}
|
|
}
|
|
|
|
function parseLine(line: string): number {
|
|
const matches = line.matchAll(DIGIT_REGEX);
|
|
|
|
|
|
if (!matches) return 0;
|
|
|
|
const converted = [...matches].flatMap(((matchArray) => matchArray.map(parseDigit))).filter(digit => digit.length);
|
|
|
|
console.log(converted);
|
|
const str = `${converted[0]}${converted[converted.length - 1]}`;
|
|
const parsed = parseInt(str, 10);
|
|
|
|
if (isNaN(parsed)) {
|
|
return 0;
|
|
}
|
|
|
|
return parsed;
|
|
|
|
}
|
|
|
|
function calculateCalibration(lines: string[]): number {
|
|
return lines.reduce((calibration, line) => {
|
|
const parsed = parseLine(line);
|
|
|
|
if (isNaN(parsed)) {
|
|
return calibration;
|
|
}
|
|
return calibration + parsed;
|
|
}, 0);
|
|
}
|
|
|
|
function dayOne() {
|
|
const lines = fs.readFileSync("./inputs/day_one.txt").toString('utf-8').split('\n');
|
|
console.log(calculateCalibration(lines));
|
|
}
|
|
|
|
function test() {
|
|
const expected = 83;
|
|
const result = calculateCalibration([
|
|
'two1nine',
|
|
'eightwothree',
|
|
'abcone2threexyz',
|
|
'xtwone3four',
|
|
'4nineeightseven2',
|
|
'zoneight234',
|
|
'7pqrstsixteen',
|
|
'eighthree',
|
|
'sevenine'
|
|
])
|
|
if (result !== expected) {
|
|
throw new Error(`Expected ${expected} but got ${result}`);
|
|
}
|
|
}
|
|
test();
|
|
dayOne(); |