|
| 1 | +from aocd import submit |
| 2 | +from aoc import * |
| 3 | +from collections import defaultdict, deque |
| 4 | +from itertools import combinations |
| 5 | +from pprint import pprint |
| 6 | +from math import sqrt |
| 7 | +import re |
| 8 | +import functools |
| 9 | + |
| 10 | + |
| 11 | +FILE = "22_test.txt" |
| 12 | +FILE = "22.txt" |
| 13 | + |
| 14 | + |
| 15 | +def recursive_combat(hand1, hand2): |
| 16 | + games = set() |
| 17 | + while len(hand1) > 0 and len(hand2) > 0: |
| 18 | + game = (tuple(hand1), tuple(hand2)) |
| 19 | + if game in games: |
| 20 | + score = 0 |
| 21 | + for i, c in enumerate(hand1): |
| 22 | + score += (len(hand1)-i) * c |
| 23 | + return 'player1' |
| 24 | + games.add(game) |
| 25 | + card1 = hand1.popleft() |
| 26 | + card2 = hand2.popleft() |
| 27 | + if card1 <= len(hand1) and card2 <= len(hand2): |
| 28 | + winner = recursive_combat(deque(list(hand1)[:card1]), deque(list(hand2)[:card2])) |
| 29 | + if winner == 'player1': |
| 30 | + hand1.extend((card1, card2)) |
| 31 | + elif winner == 'player2': |
| 32 | + hand2.extend((card2, card1)) |
| 33 | + else: |
| 34 | + hand1.extend((card1, card2)) |
| 35 | + return 'instant' |
| 36 | + else: |
| 37 | + if card1 > card2: |
| 38 | + hand1.extend((card1, card2)) |
| 39 | + else: |
| 40 | + hand2.extend((card2, card1)) |
| 41 | + |
| 42 | + if len(hand1) > 0: |
| 43 | + return 'player1' |
| 44 | + else: |
| 45 | + return 'player2' |
| 46 | + |
| 47 | + |
| 48 | +def main(): |
| 49 | + inp = file(FILE).rstrip() |
| 50 | + p1,p2 = inp.split('\n\n') |
| 51 | + p1 = p1.split('\n')[1:] |
| 52 | + p2 = p2.split('\n')[1:] |
| 53 | + print(p1) |
| 54 | + print() |
| 55 | + print(p2) |
| 56 | + p1 = [int(x) for x in p1] |
| 57 | + p2 = [int(x) for x in p2] |
| 58 | + hand1 = deque(p1) |
| 59 | + hand2 = deque(p2) |
| 60 | + out = 0 |
| 61 | + games = set() |
| 62 | + winner = recursive_combat(hand1, hand2, games) |
| 63 | + if winner == 'instant': |
| 64 | + winner = 'player1' |
| 65 | + if winner == 'player1': |
| 66 | + h = hand1 |
| 67 | + else: |
| 68 | + h = hand2 |
| 69 | + score = 0 |
| 70 | + for i, c in enumerate(h): |
| 71 | + score += (len(h)-i) * c |
| 72 | + out = score |
| 73 | + print(out) |
| 74 | + return |
| 75 | + input() |
| 76 | + print("submitting") |
| 77 | + submit(out) |
| 78 | + |
| 79 | + |
| 80 | +main() |
0 commit comments