summaryrefslogtreecommitdiff
path: root/day-3/script.ts
blob: f693928a7cff218efcc6df8e9cd8253de87f733f (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
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 = symbols
  .filter((symbol) => symbol.symbol === "*")
  .reduce((acc, symbol) => {
    const adjacentNumbers = numbers.filter(
      (number) =>
        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),
    );

    return adjacentNumbers.length === 2
      ? acc + adjacentNumbers[0].number * adjacentNumbers[1].number
      : acc;
  }, 0);

console.log({ result });