summaryrefslogtreecommitdiffstats
path: root/day2/__init__.py
blob: c45287889a0b87f6c1f3b8031f0aa03636b81db8 (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
70
71
72
73
74
75
76
77
78
79
# -*- coding: utf-8 -*-
from abc import ABC
from enum import Enum
from functools import reduce
from typing import Iterator

from aoc import BaseAssignment, I, T


class Color(Enum):
    red = "red"
    green = "green"
    blue = "blue"


ColorCount = tuple[int, Color]


class Assignment(BaseAssignment, ABC):
    def parse_item(self, item: str) -> list[tuple[ColorCount, ...]]:
        _, items = item.split(": ")

        return [
            tuple(
                ColorCount((int(_.split(" ")[0]), Color(_.split(" ")[1])))
                for _ in pair.split(", ")
            )
            for pair in items.split("; ")
        ]


class AssignmentOne(Assignment):
    example_result = 8

    inventory = {
        Color.red: 12,
        Color.green: 13,
        Color.blue: 14,
    }

    def is_possible(self, game: list[tuple[ColorCount, ...]]):
        for item in game:
            for count, color in item:
                if count > self.inventory[color]:
                    return False

        return True

    def run(self, input: Iterator[list[tuple[ColorCount, ...]]]) -> int:
        possible_games = []

        for index, game in enumerate(input):
            if self.is_possible(game):
                possible_games.append(index + 1)

        return sum(possible_games)


class AssignmentTwo(Assignment):
    example_result = 2286

    def get_least_numbers(self, game: list[tuple[ColorCount, ...]]):
        counts = {}

        for item in game:
            for count, color in item:
                if color not in counts or count > counts[color]:
                    counts[color] = count

        return counts

    def run(self, input: Iterator[list[tuple[ColorCount, ...]]]) -> int:
        powers = []

        for game in input:
            counts = self.get_least_numbers(game)
            powers.append(reduce(lambda total, item: total * item, counts.values(), 1))

        return sum(powers)