summaryrefslogtreecommitdiff
path: root/day-1/script.ts
blob: 83989220aa191aa0496a4784f65fb8e0d48d0981 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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(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[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 });