59 lines
1.6 KiB
Python
Executable file
59 lines
1.6 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
|
|
# https://adventofcode.com/2023/day/2
|
|
|
|
import re
|
|
|
|
|
|
def get_lines(filename: str) -> list:
|
|
with open(filename, "r") as file:
|
|
return [line.strip() for line in file.readlines()]
|
|
|
|
|
|
def get_games(lines: list) -> dict:
|
|
games = {}
|
|
for line in lines:
|
|
game_number, grabs = line.split(": ")
|
|
game_number = game_number[5:] # shave off "Game " from string
|
|
games[int(game_number)] = grabs
|
|
return games
|
|
|
|
|
|
def get_max_cubes(grabs: str) -> dict:
|
|
max_cubes = {}
|
|
for grab in grabs.split(";"):
|
|
for cube_string in grab.split(", "):
|
|
num_cubes_str, colour = cube_string.split()
|
|
num_cubes = int(num_cubes_str)
|
|
if colour not in max_cubes or num_cubes > max_cubes[colour]:
|
|
max_cubes[colour] = num_cubes
|
|
return max_cubes
|
|
|
|
|
|
def game_is_valid(game: dict, cube_pools: dict) -> bool:
|
|
for colour in game.keys():
|
|
if colour not in cube_pools or game[colour] > cube_pools[colour]:
|
|
return False
|
|
return True
|
|
|
|
|
|
def sum_of_valid_games(games: dict, cube_pools: dict) -> int:
|
|
valid_games = 0
|
|
for game_num in games.keys():
|
|
grabs = games[game_num]
|
|
max_cubes = get_max_cubes(grabs)
|
|
if game_is_valid(max_cubes, cube_pools):
|
|
valid_games += game_num
|
|
return valid_games
|
|
|
|
|
|
def main():
|
|
lines = get_lines("input.txt")
|
|
cube_pools = {"red": 12, "green": 13, "blue": 14}
|
|
games = get_games(lines)
|
|
result = sum_of_valid_games(games, cube_pools)
|
|
print(f"Part 1: The sum of valid games is: {result}")
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|