Day 2: Cube Conundrum


Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ or pastebin (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ


🔒This post will be unlocked when there is a decent amount of submissions on the leaderboard to avoid cheating for top spots

🔓 Edit: Post has been unlocked after 6 minutes

  • hades
    link
    fedilink
    arrow-up
    2
    ·
    7 months ago

    Python

    Questions and feedback welcome!

    import collections
    
    from .solver import Solver
    
    class Day02(Solver):
      def __init__(self):
        super().__init__(2)
        self.games = []
    
      def presolve(self, input: str):
        lines = input.rstrip().split('\n')
        for line in lines:
          draws = line.split(': ')[1].split('; ')
          draws = [draw.split(', ') for draw in draws]
          self.games.append(draws)
    
      def solve_first_star(self):
        game_id = 0
        total = 0
        for game in self.games:
          game_id += 1
          is_good = True
          for draw in game:
            for item in draw:
              count, colour = item.split(' ')
              if (colour == 'red' and int(count) > 12 or  # pylint: disable=too-many-boolean-expressions
                    colour == 'blue' and int(count) > 14 or
                    colour == 'green' and int(count) > 13):
                is_good = False
          if is_good:
            total += game_id
        return total
    
      def solve_second_star(self):
        total = 0
        for game in self.games:
          minimums = collections.defaultdict(lambda: 0)
          for draw in game:
            for item in draw:
              count, colour = item.split(' ')
              minimums[colour] = max(minimums[colour], int(count))
          power = minimums['red'] * minimums['blue'] * minimums['green']
          total += power
        return total