Skip to content

Instantly share code, notes, and snippets.

@kung-foo
Created December 22, 2020 08:46
Show Gist options
  • Save kung-foo/fc665be389df0b8d58b2c023e9f99faa to your computer and use it in GitHub Desktop.
Save kung-foo/fc665be389df0b8d58b2c023e9f99faa to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import os
import sys
import random
src = open("input.txt", "r").readlines()
src2 = """
Player 1:
9
2
6
3
1
Player 2:
5
8
4
7
10
""".splitlines()
src2 = """
Player 1:
43
19
Player 2:
2
29
14""".splitlines()
src = [r.strip() for r in src if r.strip()]
deck1 = []
deck2 = []
d = None
for line in src:
if line == "Player 1:":
d = deck1
continue
if line == "Player 2:":
d = deck2
continue
d.append(int(line))
def play_game(mode: int, d1: list, d2: list):
played = set()
while d1 and d2:
c1 = d1.pop(0)
c2 = d2.pop(0)
if mode == 2 and len(d1) >= c1 and len(d2) >= c2:
p1, p2 = play_game(mode, d1[0:c1], d2[0:c2])
if p1:
d1.extend([c1, c2])
else:
d2.extend([c2, c1])
else:
if c1 > c2:
d1.extend([c1, c2])
else:
d2.extend([c2, c1])
h1 = hash(tuple(d1))
if h1 in played:
print("C-c-c-c-c-combo breaker")
return True, False
played.add(h1)
return len(d1) > 0, len(d2) > 0
def score(d1: list, d2: list):
c1 = 0
c2 = 0
for i in range(1, len(d1) + 1):
c1 += i * d1[-i]
for i in range(1, len(d2) + 1):
c2 += i * d2[-i]
return c1, c2
d1 = deck1.copy()
d2 = deck2.copy()
play_game(1, d1, d2)
print(score(d1, d2))
###
d1 = deck1.copy()
d2 = deck2.copy()
play_game(2, d1, d2)
print(score(d1, d2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment