You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
83 lines
2.1 KiB
83 lines
2.1 KiB
#!/usr/bin/env python3
|
|
|
|
import sys, re
|
|
|
|
def memo(fc):
|
|
memo = {}
|
|
def f2(a,b,c,d,e,f,g):
|
|
if (a,b,c,d,e,f,g) not in memo: memo[(a,b,c,d,e,f,g)] = fc(a,b,c,d,e,f,g)
|
|
return memo[(a,b,c,d,e,f,g)]
|
|
return f2
|
|
|
|
def parse(line):
|
|
groups = re.compile(r"Player 1 starting position: (?P<p1>\d+)\nPlayer 2 starting position: (?P<p2>\d+)").search(line)
|
|
return groups
|
|
|
|
def step(p1,p2):
|
|
d,s1,s2,die,dr = 0,0,0,0,0
|
|
t = 1
|
|
while s1 < 1000 and s2 < 1000:
|
|
mv = d*3 + 6
|
|
d = d + 3 % 100
|
|
dr += 3
|
|
if t == 1:
|
|
p1 = (p1 + mv - 1) % 10 + 1
|
|
s1 += p1
|
|
if t == 2:
|
|
p2 = (p2 + mv - 1) % 10 + 1
|
|
s2 += p2
|
|
t = t%2+1
|
|
return dr*s2 if s2 < 1000 else dr*s1
|
|
|
|
@memo
|
|
def qstep(p1,p2,s1,s2,dv,t,dt):
|
|
if s1 >= 21:
|
|
return {1:1,2:0}
|
|
elif s2 >= 21:
|
|
return {1:0,2:1}
|
|
wins = {1: 0, 2: 0}
|
|
if t == 1:
|
|
if dt == 3:
|
|
nt = t%2+1
|
|
np1 = (p1 + dv - 1) % 10 + 1
|
|
ns1 = s1+np1
|
|
win = qstep(np1,p2,ns1,s2,0,nt,0)
|
|
wins[1] += win[1]
|
|
wins[2] += win[2]
|
|
else:
|
|
dt += 1
|
|
for d in range(1,4):
|
|
ndv = dv+d
|
|
win = qstep(p1,p2,s1,s2,ndv,t,dt)
|
|
wins[1] += win[1]
|
|
wins[2] += win[2]
|
|
if t == 2:
|
|
if dt == 3:
|
|
nt = t%2+1
|
|
np2 = (p2 + dv - 1) % 10 + 1
|
|
ns2 = s2+np2
|
|
win = qstep(p1,np2,s1,ns2,0,nt,0)
|
|
wins[1] += win[1]
|
|
wins[2] += win[2]
|
|
else:
|
|
dt += 1
|
|
for d in range(1,4):
|
|
ndv = dv+d
|
|
win = qstep(p1,p2,s1,s2,ndv,t,dt)
|
|
wins[1] += win[1]
|
|
wins[2] += win[2]
|
|
return wins
|
|
|
|
if __name__ == '__main__':
|
|
p1,p2 = map(int,parse(open(sys.argv[1]).read()).groups())
|
|
|
|
# challenge 1
|
|
res1 = str(step(p1,p2))
|
|
print("challenge 1:" + "\n" + res1 + "\n")
|
|
|
|
# challenge 2
|
|
results = qstep(p1,p2,0,0,0,1,0)
|
|
|
|
res2 = str(max(results.values()))
|
|
print("challenge 2:" + "\n" + res2 + "\n")
|
|
|
|
|