84 lines
2.3 KiB
Python
84 lines
2.3 KiB
Python
import re
|
|
from dataclasses import dataclass
|
|
|
|
|
|
def run():
|
|
game = GameRecord(r"./src/assets/day_2.txt")
|
|
print(f"Total games valid: {game.sum_valid()}")
|
|
print(f"Total games power: {game.sum_power()}")
|
|
|
|
|
|
@dataclass
|
|
class Game:
|
|
id: int
|
|
plays: list[list[tuple]]
|
|
|
|
|
|
class GameRecord:
|
|
path: str
|
|
games: list[Game]
|
|
|
|
def __init__(self, path: str):
|
|
self.path = path
|
|
self.games = self.read_games()
|
|
|
|
def sum_valid(self):
|
|
sum = 0
|
|
for game in self.games:
|
|
red = 0
|
|
green = 0
|
|
blue = 0
|
|
for play in game.plays:
|
|
for item in play:
|
|
match item[1]:
|
|
case "blue":
|
|
blue = max(blue,int(item[0]))
|
|
case "red":
|
|
red = max(red, int(item[0]))
|
|
case "green":
|
|
green = max(green,int(item[0]))
|
|
|
|
if red <= 12 and green <= 13 and blue <= 14:
|
|
sum += game.id
|
|
|
|
return sum
|
|
|
|
def sum_power(self):
|
|
sum = 0
|
|
for game in self.games:
|
|
red = 0
|
|
green = 0
|
|
blue = 0
|
|
for play in game.plays:
|
|
for item in play:
|
|
match item[1]:
|
|
case "blue":
|
|
blue = max(blue,int(item[0]))
|
|
case "red":
|
|
red = max(red, int(item[0]))
|
|
case "green":
|
|
green = max(green,int(item[0]))
|
|
|
|
sum += red * green * blue
|
|
|
|
return sum
|
|
|
|
def read_games(self) -> list[Game]:
|
|
with open(self.path) as file:
|
|
lines = file.readlines()
|
|
games = []
|
|
|
|
for line in lines:
|
|
game_parsed = re.findall(
|
|
r"^Game ([0-9]+):(.*)", line
|
|
)
|
|
game_plays_raw = str(game_parsed[0][1]).split(";")
|
|
game_id = int(game_parsed[0][0])
|
|
game_plays = []
|
|
for play in game_plays_raw:
|
|
game_plays.append(re.findall(r"([0-9]+) (blue|red|green)", play.lstrip().rstrip()))
|
|
|
|
games.append(Game(game_id, game_plays))
|
|
|
|
return games
|