-
Notifications
You must be signed in to change notification settings - Fork 0
/
day22_part2.py
executable file
·65 lines (57 loc) · 2.71 KB
/
day22_part2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/python3
import loader
#inp = loader.string_list("input_day22")
#inp = loader.integer_list("input_day22")
inp = loader.blank_line_delimited("input_day22")
#inp = loader.CharacterGrid("input_day22")
player_1_deck = [int(num) for num in inp[0][1:]]
player_1_deck.reverse() #index 0 is bottom of deck
player_2_deck = [int(num) for num in inp[1][1:]]
player_2_deck.reverse() #index 0 is bottom of deck
def score_deck(player_deck):
total_score = 0
for i in range(len(player_deck)):
total_score += (i+1)*player_deck[i]
return total_score
def play_recursive_combat(player_1_deck, player_2_deck):
"""
Returns a tuple: (winner, score). Winner may be 1 or 2 to indicate which player won.
Score is the winner's score.
"""
this_game_history = set() # contains tuples of deck content tuples: (tuple(deck1),tuple(deck2))
while True:
if (tuple(player_1_deck),tuple(player_2_deck)) in this_game_history:
return (1,score_deck(player_1_deck))
else:
this_game_history.add((tuple(player_1_deck),tuple(player_2_deck)))
if len(player_1_deck) == 0:
return (2,score_deck(player_2_deck))
if len(player_2_deck) == 0:
return (1,score_deck(player_1_deck))
player_1_top_card = player_1_deck.pop()
player_2_top_card = player_2_deck.pop()
if player_1_top_card <= len(player_1_deck) and player_2_top_card <= len(player_2_deck):
player_1_sub_game_deck = player_1_deck[(-1*player_1_top_card):]
player_2_sub_game_deck = player_2_deck[(-1*player_2_top_card):]
results = play_recursive_combat(player_1_sub_game_deck,
player_2_sub_game_deck)
winner = results[0]
if winner == 1:
player_1_deck.insert(0,player_1_top_card)
player_1_deck.insert(0,player_2_top_card)
elif winner == 2:
player_2_deck.insert(0,player_2_top_card)
player_2_deck.insert(0,player_1_top_card)
else:
raise RuntimeError("Two equal cards played against each other.")
else: # play a regular round
if player_1_top_card > player_2_top_card:
player_1_deck.insert(0,player_1_top_card)
player_1_deck.insert(0,player_2_top_card)
elif player_2_top_card > player_1_top_card:
player_2_deck.insert(0,player_2_top_card)
player_2_deck.insert(0,player_1_top_card)
else:
raise RuntimeError("Two equal cards played against each other.")
results = play_recursive_combat(player_1_deck,player_2_deck)
print(f"Player {results[0]} won with score {results[1]}")