123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- import { LoadInput } from "../common.ts";
- function CalculateCalibrationSum(document: string[]): number {
- return document.reduce((register, currVal) => register + extractCalibrationValue(currVal), 0);
- }
- function extractCalibrationValue(line: string): number {
- const extracter = new RegExp("(?=(one|t(?:wo|hree)|f(?:our|ive)|s(?:ix|even)|eight|nine|[0-9]))", "g");
- const digitsInString = Array.from(line.matchAll(extracter), (match) => match[1]) || [];
- if (digitsInString.length == 0) {
- console.error("No digits found on line!");
- console.error(line);
- }
- const firstDigit = parseNumberWordToDigit(digitsInString[0]);
- const secondDigit = parseNumberWordToDigit(digitsInString[digitsInString.length - 1]);
- return Number(firstDigit + secondDigit);
- }
- function parseNumberWordToDigit(numberString: string|undefined): string {
- switch (numberString) {
- case "0":
- case "1":
- case "2":
- case "3":
- case "4":
- case "5":
- case "6":
- case "7":
- case "8":
- case "9":
- return numberString;
- 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 "0";
- }
- }
- const tests: string[] = [
- "two1nine",
- "eightwothree",
- "abcone2threexyz",
- "xtwone3four",
- "4nineeightseven2",
- "zoneight234",
- "7pqrstsixteen",
- "3pqrstsevenine",
- ];
- const input = await LoadInput(1);
- console.log("Test Cases");
- console.log("Expected: 320")
- console.log(`Actual: ${CalculateCalibrationSum(tests)}\n`);
- console.log("Input");
- console.log(`Your *true* calibration sum: ${CalculateCalibrationSum(input)}`);
|