summaryrefslogtreecommitdiff
path: root/day-12/sol.ts
blob: 7143403c10862b8557a2baefb35c0d22095ee312 (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
53
54
55
56
57
58
59
import * as input from "fs";

type NestedNumbers = Array<NestedNumbers | number>;

const compare = (
  a: NestedNumbers | number,
  b: NestedNumbers | number
): boolean => {
  if (typeof a === typeof b && typeof b === "number") return a < b;
  if (Array.isArray(a) && Array.isArray(b)) {
    for (let i = 0; i < a.length; i++) {
      if (i >= b.length) return false;
      if (compare(a[i], b[i])) return true;
      if (compare(b[i], a[i])) return false;
    }
    return compare(a.length, b.length);
  }
  return compare(Array.isArray(b) ? [a] : a, Array.isArray(a) ? [b] : b);
};

const main = (): void => {
  const lines: NestedNumbers[] = input
    .readFileSync("input", "utf-8")
    .split("\n")
    .filter((x) => x)
    .map((x) => JSON.parse(x));

  const pairs: [NestedNumbers, NestedNumbers][] = [];
  for (let i = 0; i < lines.length; i += 2) {
    const pair: [NestedNumbers, NestedNumbers] = [lines[i], lines[i + 1]];
    pairs.push(pair);
  }

  console.log(
    pairs.reduce((acc, [a, b], i) => acc + (compare(a, b) ? i + 1 : 0), 0)
  );

  lines.push([[2]]);
  lines.push([[6]]);

  const sorted = lines.sort((a, b) => {
    if (compare(a, b)) return -1;
    if (compare(b, a)) return 1;
    return 0;
  });

  const isPacket = (num: number) => (x: NestedNumbers) =>
    Array.isArray(x) &&
    x.length === 1 &&
    Array.isArray(x[0]) &&
    x[0].length === 1 &&
    x[0][0] === num;

  console.log(
    (sorted.findIndex(isPacket(6)) + 1) * (sorted.findIndex(isPacket(2)) + 1)
  );
};

main();