Skip to content

Instantly share code, notes, and snippets.

@vjeranc
Created December 19, 2023 07:33
Show Gist options
  • Save vjeranc/f5cbb1884f205675206e22d238267217 to your computer and use it in GitHub Desktop.
Save vjeranc/f5cbb1884f205675206e22d238267217 to your computer and use it in GitHub Desktop.
import re
wf, pt = open(0).read().split('\n\n')
wfd = {}
for l in wf.split():
w, cs = l.split('{')
cd = list()
conds = cs[:-1].split(',')
for i, c in enumerate(conds):
if i+1==len(conds):
cd.append((c, )+(None, )*3)
break
k, dest = c.split(':')
f, v = re.split(r'[<>]', k)
cd.append((dest, f, '<' in k, int(v)))
wfd[w] = cd
wfd['A'] = [('A', )+(None, )*3]
wfd['R'] = [('R', )+(None, )*3]
pd = []
for l in pt.split():
props = l[1:-1].split(',')
part = dict()
for p in props:
k, v = p.split('=')
part[k] = int(v)
pd.append(part)
ans = 0
for part in pd:
cs = 'in'
while cs not in ['A', 'R']:
cds = wfd[cs]
for dest, f, less, cv in cds[:-1]:
v = part[f]
if less and v<cv:
cs = dest
break
elif not less and v>cv:
cs = dest
break
else:
cs = cds[-1][0]
if cs=='A':
ans += sum(part.values())
print(ans)
def shrink(xlh, f, rs):
xl, xh = xlh
ans = []
for r in rs:
x, y = r[f]
x, y = max(xl, x), min(xh, y)
if x>=y: continue
r[f] = x, y
ans.append(r)
return ans
def dfs(cs):
dest, f, less, v = cs[0]
if f is None and dest=='R': return []
if f is None and dest=='A': return [dict((c, (1, 4001)) for c in 'xmas')]
if f is None: return dfs(wfd[dest])
rs1 = shrink((1, v) if less else (v+1, 4001), f, dfs(wfd[dest])) # accept
rs2 = shrink((v, 4001) if less else (1, v+1), f, dfs(cs[1:])) # reject
return rs1+rs2
ans = 0
for d in dfs([('in', )+(None, )*3]):
p = 1
for l, r in d.values():
p *= r-l
ans += p
print(ans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment