-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart_one.py
81 lines (59 loc) · 1.98 KB
/
part_one.py
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
80
81
from enum import StrEnum, unique
from typing import override
from infrastructure.solutions.base import Solution
GAME_ID = int
CUBES_COUNT = tuple[str, int]
@unique
class CubeColor(StrEnum):
RED = 'red'
GREEN = 'green'
BLUE = 'blue'
class Year2023Day2Part1Solution(Solution):
RED_CUBES = 12
GREEN_CUBES = 13
BLUE_CUBES = 14
@classmethod
@override
def parse_input(cls, text_input: str) -> dict[str, dict[GAME_ID, list[CUBES_COUNT]]]:
games = {}
for line in text_input.split('\n'):
if not line:
continue
# Game <ID>: <game>
game_id, game = line.split(': ')
game_id = int(game_id.removeprefix('Game '))
games[game_id] = []
# <subset1>; <subset2>; ...
for subset in game.split('; '):
# <cubes1>, <cubes2>, ...
for cubes in subset.split(', '):
# <count> <color>
count, color = cubes.split()
games[game_id].append((color, int(count)))
return {'games': games}
@classmethod
@override
def solve(cls, games: dict[GAME_ID, list[CUBES_COUNT]]) -> int:
"""
Time: O(n*m)
Space: O(1)
Where n - total number of games,
m - maximum game size
"""
ids_sum = 0
for game_id, game in games.items():
if cls.is_game_possible(game):
ids_sum += game_id
return ids_sum
@classmethod
def is_game_possible(cls, game: list[CUBES_COUNT]) -> bool:
for color, count in game:
if color == CubeColor.RED and count > cls.RED_CUBES:
return False
if color == CubeColor.GREEN and count > cls.GREEN_CUBES:
return False
if color == CubeColor.BLUE and count > cls.BLUE_CUBES:
return False
return True
if __name__ == '__main__':
print(Year2023Day2Part1Solution.main())