82 lines
2.4 KiB
Python
82 lines
2.4 KiB
Python
import copy
|
|
|
|
def playRound(p1,p2):
|
|
if p1[0]>p2[0]:
|
|
p1.append(p1[0])
|
|
p1.pop(0)
|
|
p1.append(p2[0])
|
|
p2.pop(0)
|
|
elif p2[0]>p1[0]:
|
|
p2.append(p2[0])
|
|
p2.pop(0)
|
|
p2.append(p1[0])
|
|
p1.pop(0)
|
|
return [p1,p2]
|
|
|
|
def calcScore(deck):
|
|
out = 0
|
|
for i in range(0,len(deck)):
|
|
print(str(i+1)+"th last card in the deck: "+str(deck[-(i+1)]))
|
|
print("value: "+str((i+1)*deck[-(i+1)]))
|
|
out += (i+1)*deck[-(i+1)]
|
|
print("running total: "+str(out))
|
|
return out
|
|
|
|
def normalGame(p1,p2):
|
|
while len(p1) > 0 and len(p2) > 0:
|
|
res = playRound(p1, p2)
|
|
p1 = res[0]
|
|
p2 = res[1]
|
|
return [p1,p2]
|
|
|
|
def recurseGame(p1,p2,n):
|
|
print("start subgame of level "+str(n))
|
|
rounds = []
|
|
while len(p1) > 0 and len(p2) > 0:
|
|
if [p1,p2] in rounds:
|
|
print("subgame level " + str(n) + " has ended")
|
|
return [p1,[]]
|
|
if p1[0] <= len(p1)-1 and p2[0] <= len(p2)-1:
|
|
res = recurseGame(copy.deepcopy(p1[1:(p1[0]+1)]),copy.deepcopy(p2[1:(p2[0]+1)]),n+1)
|
|
if len(res[0])>0:
|
|
p1.append(p1[0])
|
|
p1.pop(0)
|
|
p1.append(p2[0])
|
|
p2.pop(0)
|
|
elif len(res[1])>0:
|
|
p2.append(p2[0])
|
|
p2.pop(0)
|
|
p2.append(p1[0])
|
|
p1.pop(0)
|
|
else:
|
|
print("THIS IS AN ERROR")
|
|
else:
|
|
res = playRound(copy.deepcopy(p1),copy.deepcopy(p2))
|
|
rounds.append([copy.deepcopy(p1),copy.deepcopy(p2)])
|
|
p1 = res[0]
|
|
p2 = res[1]
|
|
print("subgame level "+str(n)+" has ended")
|
|
return[p1,p2]
|
|
|
|
|
|
p1 = []
|
|
p2 = []
|
|
flag = False
|
|
with open("input22.txt") as file:
|
|
for line in file:
|
|
if line == "Player 1:\n":
|
|
pass
|
|
elif line == "Player 2:\n":
|
|
flag = True
|
|
elif line == "\n":
|
|
pass
|
|
elif not flag:
|
|
p1.append(int(line[:-1]))
|
|
else:
|
|
p2.append(int(line[:-1]))
|
|
norm = normalGame(copy.deepcopy(p1),copy.deepcopy(p2))
|
|
scnorm = calcScore(norm[0]) if len(norm[0])>0 else calcScore(norm[1])
|
|
rec = recurseGame(copy.deepcopy(p1),copy.deepcopy(p2),0)
|
|
screc = calcScore(rec[0]) if len(rec[0])>0 else calcScore(rec[1])
|
|
print("Normal game winner has score of " + str(scnorm))
|
|
print("Recursive game winner has score of " + str(screc)) |