|
| 1 | +# MIT License |
| 2 | +# |
| 3 | +# Copyright (c) 2021 Andrew Krepps |
| 4 | +# |
| 5 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 6 | +# of this software and associated documentation files (the "Software"), to deal |
| 7 | +# in the Software without restriction, including without limitation the rights |
| 8 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 9 | +# copies of the Software, and to permit persons to whom the Software is |
| 10 | +# furnished to do so, subject to the following conditions: |
| 11 | +# |
| 12 | +# The above copyright notice and this permission notice shall be included in all |
| 13 | +# copies or substantial portions of the Software. |
| 14 | +# |
| 15 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 18 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 20 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 21 | +# SOFTWARE. |
| 22 | + |
| 23 | + |
| 24 | +from . import util |
| 25 | + |
| 26 | + |
| 27 | +def parse_input(lines): |
| 28 | + deck = [] |
| 29 | + all_decks = [] |
| 30 | + for line in lines: |
| 31 | + if line.startswith("Player"): |
| 32 | + if deck: |
| 33 | + all_decks.append(deck) |
| 34 | + deck = [] |
| 35 | + else: |
| 36 | + deck.insert(0, int(line)) |
| 37 | + all_decks.append(deck) |
| 38 | + return all_decks |
| 39 | + |
| 40 | + |
| 41 | +def calculate_score(deck): |
| 42 | + score = 0 |
| 43 | + for idx, card in enumerate(deck): |
| 44 | + score += (idx + 1) * card |
| 45 | + return score |
| 46 | + |
| 47 | + |
| 48 | +def play_game(all_decks): |
| 49 | + num_cards = sum(len(deck) for deck in all_decks) |
| 50 | + while max(len(deck) for deck in all_decks) < num_cards: |
| 51 | + played_cards = [(player_idx, deck.pop()) for player_idx, deck in enumerate(all_decks) if deck] |
| 52 | + played_cards.sort(key=lambda x: x[1], reverse=True) |
| 53 | + winning_player_idx = played_cards[0][0] |
| 54 | + for _, card in played_cards: |
| 55 | + all_decks[winning_player_idx].insert(0, card) |
| 56 | + return max(calculate_score(deck) for deck in all_decks) |
| 57 | + |
| 58 | + |
| 59 | +def get_part1_answer(lines): |
| 60 | + all_decks = parse_input(lines) |
| 61 | + return play_game(all_decks) |
| 62 | + |
| 63 | + |
| 64 | +def get_part2_answer(lines): |
| 65 | + return None |
| 66 | + |
| 67 | + |
| 68 | +def run(): |
| 69 | + lines = util.get_input_file_lines("day22.txt") |
| 70 | + print(f"The answer to part 1 is {get_part1_answer(lines)}") |
| 71 | + print(f"The answer to part 2 is {get_part2_answer(lines)}") |
0 commit comments