summaryrefslogtreecommitdiff
path: root/aoc_2023/day-04/part_2.ts
blob: e50f14d4bfa49cf3308af82aa8f28251c9c8c83d (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
60
61
62
export const main = async (lines: string[]): Promise<number | string> => {
  let card = 0;
  const counts = new Map<number, number>();
  lines.forEach((_, i) => counts.set(i, 1));

  for (const line of lines) {
    const [cardS, numbersS] = line.split(" | ");
    const cardNums = cardS
      .split(":")
      .at(1)!
      .split(" ")
      .filter((x) => x)
      .map((x) => x.trim())
      .map((x) => parseInt(x));
    const winners = numbersS
      .split(" ")
      .filter((x) => x)
      .map((x) => x.trim())
      .map((x) => parseInt(x));

    const winnerSet = new Set<number>(winners);
    const wins = cardNums.reduce(
      (acc, x) => acc + (winnerSet.has(x) ? 1 : 0),
      0
    );

    const currCardCount = counts.get(card) ?? 1;

    for (let _ = 0; _ < currCardCount; _++) {
      for (let i = 1; i <= Math.min(wins, lines.length - 1); i++) {
        const currCount = counts.get(card + i) ?? 1;
        counts.set(card + i, currCount + 1);
      }
    }

    card++;
  }

  console.log(counts);

  return Array.from(counts.keys())
    .map((x) => counts.get(x)!)
    .reduce((acc, x) => acc + x, 0);
};

//

const isrun = process.argv.length > 1 && process.argv[1] === import.meta.path;
if (isrun) {
  const file = Bun.file("./problem.txt");
  const text = await file.text();
  const lines = text.split("\n").filter((x) => x && x.length);

  console.log("=== COMPUTATION ===\n");

  const answer = await main(lines);

  console.log("\n=== /COMPUTATION ===\n");

  console.log("=== ANSWER TO P2 ===");
  console.log(answer);
}