diff options
author | eug-vs <eugene@eug-vs.xyz> | 2023-12-01 15:41:16 +0300 |
---|---|---|
committer | eug-vs <eugene@eug-vs.xyz> | 2023-12-01 15:41:16 +0300 |
commit | dd4171f8253aeefaebc97126543f664cbdafcdc8 (patch) | |
tree | e6521bac43fb5276ecaaeab25a6a96b592edbae0 | |
parent | 2b46414178af362b8134bbbf2459370bd67c6aa1 (diff) | |
download | aoc-2023-dd4171f8253aeefaebc97126543f664cbdafcdc8.tar.gz |
feat(day-1): add part 2 solution
Right to left match is not that simple huh?
-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 }); |