22.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. lines = []
  2. with open("22.input") as f:
  3. for line in f.readlines():
  4. lines.append(line.strip())
  5. split_index = lines.index("Player 2:")
  6. d1 = [int(i) for i in lines[1:split_index-1]]
  7. d2 = [int(i) for i in lines[split_index+1:]]
  8. def combat(d1, d2):
  9. while d1 != [] and d2 != []:
  10. p1 = d1.pop(0)
  11. p2 = d2.pop(0)
  12. if p1 > p2:
  13. d1.append(p1)
  14. d1.append(p2)
  15. else:
  16. d2.append(p2)
  17. d2.append(p1)
  18. return d1 if d1 != [] else d2
  19. def calc_score(win_deck):
  20. win_deck.reverse()
  21. score = sum([k * x for (k, x) in zip(win_deck, range(1, len(win_deck) + 1))])
  22. win_deck.reverse()
  23. return score
  24. print("Answer 1:", calc_score(combat(list(d1), list(d2))))
  25. def recursive_combat(d1, d2):
  26. round = 1
  27. previous_rounds = set()
  28. while d1 != [] and d2 != []:
  29. #print("-- Round {} --".format(round))
  30. #print("Player 1's deck:", d1)
  31. #print("Player 2's deck:", d2)
  32. p1 = d1.pop(0)
  33. p2 = d2.pop(0)
  34. #print("Player 1 plays:", p1)
  35. #print("Player 2 plays:", p2)
  36. if (tuple(d1), tuple(d2)) in previous_rounds:
  37. return (1, [])
  38. previous_rounds.add((tuple(d1), tuple(d2)))
  39. if len(d1) >= p1 and len(d2) >= p2:
  40. winner, win_deck = recursive_combat(list(d1[0:p1]), list(d2[0:p2]))
  41. else:
  42. winner = 1 if p1 > p2 else 2
  43. #print("Player {} wins round {}".format(winner, round))
  44. if winner == 1:
  45. d1 += [p1, p2]
  46. else:
  47. d2 += [p2, p1]
  48. return (1, d1) if d1 != [] else (2, d2)
  49. print("Answer 2:", calc_score(recursive_combat(d1, d2)[1]))