78 lines
1.6 KiB
Python
78 lines
1.6 KiB
Python
|
with open("input_sample.txt") as f:
|
||
|
p1, p2 = f.read().split('\n\n')
|
||
|
p1 = p1.split('\n')[1:]
|
||
|
p2 = p2.split('\n')[1:]
|
||
|
p1 = list(map(int, p1))
|
||
|
p2 = list(map(int, p2))
|
||
|
|
||
|
i = 1
|
||
|
while True:
|
||
|
#print(f"-- Round {i} --")
|
||
|
#print("Player 1's deck: ", p1)
|
||
|
#print("Player 2's deck: ", p2)
|
||
|
c1 = p1.pop(0)
|
||
|
c2 = p2.pop(0)
|
||
|
#print("Player 1 plays: ",c1)
|
||
|
#print("Player 2 plays: ",c2)
|
||
|
if c1 > c2:
|
||
|
#print("Player 1 wins the round!")
|
||
|
p1 += [c1, c2]
|
||
|
else:
|
||
|
#print("Player 2 wins the round!")
|
||
|
p2 += [c2, c1]
|
||
|
i += 1
|
||
|
#print(p1,p2)
|
||
|
if len(p1) == 0:
|
||
|
winner = p2
|
||
|
break
|
||
|
if len(p2) == 0:
|
||
|
winner = p1
|
||
|
break
|
||
|
part1 = 0
|
||
|
for i, card in enumerate(reversed(winner)):
|
||
|
part1 += (i+1)*card
|
||
|
print(part1)
|
||
|
|
||
|
with open("input.txt") as f:
|
||
|
p1, p2 = f.read().split('\n\n')
|
||
|
p1 = p1.split('\n')[1:]
|
||
|
p2 = p2.split('\n')[1:]
|
||
|
p1 = list(map(int, p1))
|
||
|
p2 = list(map(int, p2))
|
||
|
|
||
|
def play(p1, p2):
|
||
|
seen = set()
|
||
|
while True:
|
||
|
# does p1 auto-win?
|
||
|
state = (tuple(p1), tuple(p2))
|
||
|
if state in seen:
|
||
|
return 1, p1
|
||
|
seen.add(state)
|
||
|
# draw cards
|
||
|
c1 = p1.pop(0)
|
||
|
c2 = p2.pop(0)
|
||
|
# should we recurse?
|
||
|
if len(p1) >= c1 and len(p2) >= c2: # play recursive round
|
||
|
winner, deck = play(p1[:c1],p2[:c2]) # copy that many cards
|
||
|
if winner == 1:
|
||
|
p1 += [c1, c2]
|
||
|
else: # winner == 2
|
||
|
p2 += [c2, c1]
|
||
|
else: # play normal round
|
||
|
if c1 > c2:
|
||
|
p1 += [c1, c2]
|
||
|
else: # c2 > c1
|
||
|
p2 += [c2, c1]
|
||
|
# does anyone win by normal rules?
|
||
|
if len(p1) == 0:
|
||
|
return 2, p2
|
||
|
break
|
||
|
if len(p2) == 0:
|
||
|
return 1, p1
|
||
|
|
||
|
i, winner = play(p1, p2)
|
||
|
|
||
|
part2 = 0
|
||
|
for i, card in enumerate(reversed(winner)):
|
||
|
part2 += (i+1)*card
|
||
|
print(part2)
|