70 lines
1.8 KiB
Python
70 lines
1.8 KiB
Python
|
#!/usr/bin/env python3
|
||
|
|
||
|
lines = []
|
||
|
with open('./inputs/day02.txt') as f:
|
||
|
lines = f.readlines()
|
||
|
|
||
|
# part 1
|
||
|
games = {}
|
||
|
max_red = 12
|
||
|
max_green = 13
|
||
|
max_blue = 14
|
||
|
valid_games = []
|
||
|
|
||
|
for line in lines:
|
||
|
# parse line from format 'Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green'
|
||
|
gameid = int(line.split(':')[0].split(' ')[1])
|
||
|
|
||
|
games[gameid] = []
|
||
|
|
||
|
for pullstr in line.split(':')[1].split(';'):
|
||
|
pull = {}
|
||
|
|
||
|
for color in map(lambda x: x.strip(), pullstr.split(',')):
|
||
|
c = color.split(' ')
|
||
|
pull[c[1]] = int(c[0])
|
||
|
|
||
|
# if pull does not contain color set it to 0
|
||
|
if 'red' not in pull:
|
||
|
pull['red'] = 0
|
||
|
if 'green' not in pull:
|
||
|
pull['green'] = 0
|
||
|
if 'blue' not in pull:
|
||
|
pull['blue'] = 0
|
||
|
|
||
|
games[gameid].append(pull)
|
||
|
|
||
|
game_valid = True
|
||
|
|
||
|
for pull in games[gameid]:
|
||
|
if pull['red'] > max_red or pull['green'] > max_green or pull['blue'] > max_blue:
|
||
|
game_valid = False
|
||
|
break
|
||
|
|
||
|
if game_valid:
|
||
|
valid_games.append(gameid)
|
||
|
|
||
|
print(f'valid games: {valid_games}')
|
||
|
print(f'sum: {sum(valid_games)}')
|
||
|
|
||
|
# part 2
|
||
|
# for each game get the minimum number for each color between all pulls
|
||
|
powers = []
|
||
|
for game in games:
|
||
|
max_red = 0
|
||
|
max_green = 0
|
||
|
max_blue = 0
|
||
|
|
||
|
for pull in games[game]:
|
||
|
if pull['red'] > max_red:
|
||
|
max_red = pull['red']
|
||
|
if pull['green'] > max_green:
|
||
|
max_green = pull['green']
|
||
|
if pull['blue'] > max_blue:
|
||
|
max_blue = pull['blue']
|
||
|
|
||
|
power = max_red * max_green * max_blue
|
||
|
powers.append(power)
|
||
|
print(f'game {game}: max red: {max_red}, max green: {max_green}, max blue: {max_blue}, power: {power}')
|
||
|
|
||
|
print(f'sum: {sum(powers)}')
|