diff --git a/2020/22/22.py b/2020/22/22.py index 48a0089..da1e4b6 100644 --- a/2020/22/22.py +++ b/2020/22/22.py @@ -1,25 +1,18 @@ +import copy + def playRound(p1,p2): - print("-- ROUND RESULT --") - print("Player 1's deck: "+str(p1)) - print("Player 2's deck: "+str(p2)) - print("Player 1 plays "+str(p1[0])) - print("Player 2 plays "+str(p2[0])) if p1[0]>p2[0]: p1.append(p1[0]) p1.pop(0) p1.append(p2[0]) p2.pop(0) - print("Player 1 wins the round!") elif p2[0]>p1[0]: p2.append(p2[0]) p2.pop(0) p2.append(p1[0]) p1.pop(0) - print("Player 2 wins the round!") - print("\n\n") return [p1,p2] - def calcScore(deck): out = 0 for i in range(0,len(deck)): @@ -29,9 +22,46 @@ def calcScore(deck): print("running total: "+str(out)) return out -flag = False +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": @@ -44,12 +74,9 @@ with open("input22.txt") as file: p1.append(int(line[:-1])) else: p2.append(int(line[:-1])) -while len(p1) > 0 and len(p2) > 0: - res = playRound(p1,p2) - p1 = res[0] - p2 = res[1] -print("== Post-game results ==") -print("Player 1's deck: "+str(p1)) -print("Player 2's deck: "+str(p2)) -out = calcScore(p1) if len(p1) > 0 else calcScore(p2) -print(out) \ No newline at end of file +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)) \ No newline at end of file diff --git a/2020/22/input22.txt b/2020/22/input22.txt index 126d35a..537fcb7 100644 --- a/2020/22/input22.txt +++ b/2020/22/input22.txt @@ -50,4 +50,4 @@ Player 2: 18 4 7 -20 \ No newline at end of file +20