summaryrefslogtreecommitdiff
path: root/day-3/script.ts
blob: 1793e48d0aedbe6d62fb417debf2ba152a20ceae (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
import fs from "fs";

const input = fs.readFileSync("./input.txt").toString();

const lineLength = input.split("\n")[0].length;

const chars = input.split("\n").slice(0, -1).join("");

const numbers = Array.from(chars.matchAll(/[\d]+/g)).map((match) => ({
  number: Number(match[0]),
  position: {
    start: match.index || 0,
    end: (match.index || 0) + match[0].length,
  },
}));

const symbols = Array.from(chars.matchAll(/[^\.\d]/g)).map((match) => ({
  symbol: match[0],
  position: match.index || 0,
}));

const result = numbers
  .filter((number) => {
    return !!symbols.find(
      (symbol) =>
        symbol.position === number.position.start - 1 ||
        symbol.position === number.position.end ||
        (symbol.position >= number.position.start - 1 - lineLength &&
          symbol.position <= number.position.end - lineLength) ||
        (symbol.position >= number.position.start - 1 + lineLength &&
          symbol.position <= number.position.end + lineLength),
    );
  })
  .reduce((acc, number) => acc + number.number, 0);

console.log({ result });