Advertisement
hhoppe

Advent of code 2023 day 2

Dec 2nd, 2023 (edited)
647
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.75 KB | None | 0 0
  1. def day2(s, *, part2=False):
  2.   cubes = dict(red=12, green=13, blue=14)
  3.  
  4.   def drawn_cubes(game):
  5.     for num_cube in game.split(', '):
  6.       s_num, color = num_cube.split(' ')
  7.       yield int(s_num), color    
  8.  
  9.   def game_possible(game):
  10.     return all(num <= cubes[color] for num, color in drawn_cubes(game))
  11.  
  12.   total = 0
  13.   for game_id, line in enumerate(s.splitlines(), 1):
  14.     games = line.split(': ')[1].split('; ')
  15.     if part2:
  16.       min_cubes = dict(red=0, green=0, blue=0)
  17.       for game in games:
  18.         for num, color in drawn_cubes(game):
  19.           min_cubes[color] = max(min_cubes[color], num)
  20.       total += math.prod(min_cubes.values())
  21.     elif all(game_possible(game) for game in games):
  22.       total += game_id
  23.  
  24.   return total
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement