summaryrefslogtreecommitdiff
path: root/day-2/script.ts
blob: 29c754f9bde45db3ac9677992625d4a45602a43e (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
63
64
65
66
67
68
69
import fs from "fs";

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

const COLORS = ["red", "green", "blue"] as const;
type Color = (typeof COLORS)[number];

type Draw = Record<Color, number>;

interface Game {
  id: number;
  draws: Draw[];
}

function isPossible(
  game: Game,
  maxDraw: Draw = { red: 12, green: 13, blue: 14 },
) {
  return game.draws.reduce((acc, draw) => {
    return (
      acc &&
      COLORS.every((color) => {
        return draw[color] <= maxDraw[color];
      })
    );
  }, true);
}

function getMinimalPossibleDraw(draws: Draw[]) {
  return COLORS.reduce(
    (acc, color) => {
      acc[color] = draws.reduce((max, draw) => {
        return Math.max(draw[color], max);
      }, 0);

      return acc;
    },
    { red: 0, green: 0, blue: 0 },
  );
}

function power(draw: Draw) {
  return Object.values(draw).reduce((product, value) => product * value, 1);
}

const result = input
  .split("\n")
  .slice(0, -1)
  .map((line) => {
    const [gameStr, drawsStr] = line.split(": ");
    const id = Number(gameStr.slice("Game ".length));

    const draws = drawsStr.split("; ").map((record) => {
      const draws = record.split(", ").reduce(
        (acc, draw) => {
          const [number, color] = draw.split(" ");
          acc[color] = Number(number);
          return acc;
        },
        { red: 0, green: 0, blue: 0 },
      );
      return draws;
    });
    return { id, draws };
  })
  .map((game) => getMinimalPossibleDraw(game.draws))
  .reduce((acc, draw) => acc + power(draw), 0);

console.log({ result });