1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- lines = []
- with open("22.input") as f:
- for line in f.readlines():
- lines.append(line.strip())
- split_index = lines.index("Player 2:")
- d1 = [int(i) for i in lines[1:split_index-1]]
- d2 = [int(i) for i in lines[split_index+1:]]
- def combat(d1, d2):
- while d1 != [] and d2 != []:
- p1 = d1.pop(0)
- p2 = d2.pop(0)
- if p1 > p2:
- d1.append(p1)
- d1.append(p2)
- else:
- d2.append(p2)
- d2.append(p1)
- return d1 if d1 != [] else d2
- def calc_score(win_deck):
- win_deck.reverse()
- score = sum([k * x for (k, x) in zip(win_deck, range(1, len(win_deck) + 1))])
- win_deck.reverse()
- return score
- print("Answer 1:", calc_score(combat(list(d1), list(d2))))
- def recursive_combat(d1, d2):
- round = 1
- previous_rounds = set()
- while d1 != [] and d2 != []:
- #print("-- Round {} --".format(round))
- #print("Player 1's deck:", d1)
- #print("Player 2's deck:", d2)
- p1 = d1.pop(0)
- p2 = d2.pop(0)
- #print("Player 1 plays:", p1)
- #print("Player 2 plays:", p2)
- if (tuple(d1), tuple(d2)) in previous_rounds:
- return (1, [])
- previous_rounds.add((tuple(d1), tuple(d2)))
- if len(d1) >= p1 and len(d2) >= p2:
- winner, win_deck = recursive_combat(list(d1[0:p1]), list(d2[0:p2]))
- else:
- winner = 1 if p1 > p2 else 2
- #print("Player {} wins round {}".format(winner, round))
- if winner == 1:
- d1 += [p1, p2]
- else:
- d2 += [p2, p1]
- return (1, d1) if d1 != [] else (2, d2)
- print("Answer 2:", calc_score(recursive_combat(d1, d2)[1]))
|