diff options
Diffstat (limited to 'day-1/script.ts')
-rw-r--r-- | day-1/script.ts | 45 |
1 files changed, 41 insertions, 4 deletions
diff --git a/day-1/script.ts b/day-1/script.ts index 9e444ba..8398922 100644 --- a/day-1/script.ts +++ b/day-1/script.ts @@ -2,14 +2,51 @@ import fs from "fs"; const input = fs.readFileSync("./input.txt").toString(); +const digits = [ + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", +]; + +const re = new RegExp(`(${digits.join("|")}|\\d)`); +const invertedRe = new RegExp( + `(${digits + .map((digit) => digit.split("").reverse().join("")) + .join("|")}|\\d)`, +); + +function parseNumber(s: string) { + return s.length === 1 + ? Number(s) + : digits.findIndex((digit) => digit === s) + 1; +} + const result = input .split("\n") .slice(0, -1) - .map((line) => line.match(/\d/g)) + .map((line) => [ + line.match(re)?.[0] || "", + // Reverse the string, find the inverted match right-to-left and reverse again + line + .split("") + .reverse() + .join("") + .match(invertedRe)?.[0] + .split("") + .reverse() + .join("") || "", + ]) .reduce((acc, value) => { - if (!value) - throw new Error(`The string must contain at least one digit ${value}`); - return acc + Number(value[0] + value[value.length - 1]); + if (!value[0].length || !value[1].length) throw new Error("Match failed"); + return ( + acc + parseNumber(value[0]) * 10 + parseNumber(value[value.length - 1]) + ); }, 0); console.log({ result }); |