Browse Source

Complete day 22

Frans Bergman 4 years ago
parent
commit
d3a6377522
4 changed files with 136 additions and 0 deletions
  1. 53 0
      22.input
  2. 62 0
      22.py
  3. 13 0
      22.small.input
  4. 8 0
      22.tiny.input

+ 53 - 0
22.input

@@ -0,0 +1,53 @@
+Player 1:
+20
+28
+50
+36
+35
+15
+41
+22
+39
+45
+30
+19
+47
+38
+25
+6
+2
+27
+5
+4
+37
+24
+42
+29
+21
+
+Player 2:
+23
+43
+34
+49
+13
+48
+44
+18
+14
+9
+12
+31
+16
+26
+33
+3
+10
+1
+46
+17
+32
+11
+40
+7
+8

+ 62 - 0
22.py

@@ -0,0 +1,62 @@
+lines = []
+
+with open("22.input") as f:
+    for line in f.readlines():
+        lines.append(line.strip())
+
+
+split_index = lines.index("Player 2:")
+
+d1 = [int(i) for i in lines[1:split_index-1]]
+d2 = [int(i) for i in lines[split_index+1:]]
+
+def combat(d1, d2):
+    while d1 != [] and d2 != []:
+        p1 = d1.pop(0)
+        p2 = d2.pop(0)
+        if p1 > p2:
+            d1.append(p1)
+            d1.append(p2)
+        else:
+            d2.append(p2)
+            d2.append(p1)
+
+    return d1 if d1 != [] else d2
+
+def calc_score(win_deck):
+    win_deck.reverse()
+    score = sum([k * x for (k, x) in zip(win_deck, range(1, len(win_deck) + 1))])
+    win_deck.reverse()
+    return score
+
+print("Answer 1:", calc_score(combat(list(d1), list(d2))))
+
+def recursive_combat(d1, d2):
+    round = 1
+    previous_rounds = set()
+    while d1 != [] and d2 != []:
+        #print("-- Round {} --".format(round))
+        #print("Player 1's deck:", d1)
+        #print("Player 2's deck:", d2)
+        p1 = d1.pop(0)
+        p2 = d2.pop(0)
+        #print("Player 1 plays:", p1)
+        #print("Player 2 plays:", p2)
+        if (tuple(d1), tuple(d2)) in previous_rounds:
+            return (1, [])
+        previous_rounds.add((tuple(d1), tuple(d2)))
+        if len(d1) >= p1 and len(d2) >= p2:
+            winner, win_deck = recursive_combat(list(d1[0:p1]), list(d2[0:p2]))
+        else:
+            winner = 1 if p1 > p2 else 2
+        #print("Player {} wins round {}".format(winner, round))
+        if winner == 1:
+            d1 += [p1, p2]
+        else:
+            d2 += [p2, p1]
+
+    return (1, d1) if d1 != [] else (2, d2)
+
+print("Answer 2:", calc_score(recursive_combat(d1, d2)[1]))
+
+

+ 13 - 0
22.small.input

@@ -0,0 +1,13 @@
+Player 1:
+9
+2
+6
+3
+1
+
+Player 2:
+5
+8
+4
+7
+10

+ 8 - 0
22.tiny.input

@@ -0,0 +1,8 @@
+Player 1:
+43
+19
+
+Player 2:
+2
+29
+14