Skip to content

Instantly share code, notes, and snippets.

@jonaslindmark
Created January 1, 2023 10:41
Show Gist options
  • Save jonaslindmark/9ae1bbcc04fb3df83cb07fc9a41de80b to your computer and use it in GitHub Desktop.
Save jonaslindmark/9ae1bbcc04fb3df83cb07fc9a41de80b to your computer and use it in GitHub Desktop.
from functools import cmp_to_key, cache
import math
import re
import sys
filename = "16.in.test"
filename = "16.in"
def read():
with open(filename, "r") as i:
return [l.strip() for l in i if l.strip()]
def parse():
neighbors = dict()
values = dict()
for line in read():
name = line[6:8]
rate, = parse_ints(line)
neighbors[name] = [l.strip() for l in re.sub(".*lead(s | )to valve(s | )", "", line).split(",")]
if rate > 0:
values[name] = rate
return values, neighbors
values, neighbors = parse()
c = {}
def r(current, time, toopen):
if time == 0 or not toopen:
return 0
k = (current, time, "".join(sorted(toopen)))
if k in c:
return c[k]
best = 0
if current in values and current in toopen:
v = values[current] * (time - 1)
o = toopen.copy()
o.remove(current)
best = max(v + r(current, time - 1, o), best)
for n in neighbors[current]:
best = max(r(n, time - 1, toopen), best)
c[k] = best
return best
def part1():
print(r("AA", 30, {s for s in values}))
def part2():
m = 1 << len(values)
v = [s for s in values]
best = 0
for i in range(1, m):
a = set()
b = set()
print("{0:b}".format(i))
for j in range(len(v)):
mask = 1 << j
#print("{0:b}".format(mask))
if i & mask:
a.add(v[j])
else:
b.add(v[j])
va = r("AA", 26, a)
vb = r("AA", 26, b)
best = max(best, va + vb)
print(best)
part2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment