Răsfoiți Sursa

Solve 2020 day 22

Taddeus Kroes 5 ani în urmă
părinte
comite
851df08fac
2 a modificat fișierele cu 97 adăugiri și 0 ștergeri
  1. 44 0
      2020/22_spacecards.py
  2. 53 0
      2020/input/22

+ 44 - 0
2020/22_spacecards.py

@@ -0,0 +1,44 @@
+#!/usr/bin/env python3
+import sys
+from collections import deque
+
+def parse(f):
+    for deck in f.read().split('\n\n'):
+        yield list(map(int, deck.splitlines()[1:]))
+
+def play(a, b, rec):
+    a = deque(a)
+    b = deque(b)
+    seen = set()
+
+    while a and b:
+        if rec:
+            config = tuple(a) + (0,) + tuple(b)
+            if config in seen:
+                return True, a
+            seen.add(config)
+
+        ca = a.popleft()
+        cb = b.popleft()
+
+        if rec and ca <= len(a) and cb <= len(b):
+            reca = [a[i] for i in range(ca)]
+            recb = [b[i] for i in range(cb)]
+            a_wins_round = play(reca, recb, True)[0]
+        else:
+            a_wins_round = ca > cb
+
+        if a_wins_round:
+            a.extend((ca, cb))
+        else:
+            b.extend((cb, ca))
+
+    return bool(a), a or b
+
+def score(a, b, rec):
+    a_wins, deck = play(a, b, rec)
+    return sum((len(deck) - i) * c for i, c in enumerate(deck))
+
+a, b = parse(sys.stdin)
+print(score(a, b, False))
+print(score(a, b, True))

+ 53 - 0
2020/input/22

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