Day 16 (Part 2)

This commit is contained in:
Sebastian Seedorf
2022-12-18 20:09:49 +01:00
parent 687f0aad21
commit b5160f1f3d

37
day16/part2.py Normal file
View File

@@ -0,0 +1,37 @@
#!/usr/bin/env python3
import itertools
import random
import re
lines = (x.strip() for x in open("input.txt"))
lines = (re.search(r"([A-Z]{2}).*?(\d+).*?([A-Z]{2}(?:, [A-Z]{2})*)", line).groups() for line in lines)
nodes = {name: (int(p), neighbors.split(", ")) for name, p, neighbors in lines}
def solve(positions, lasts, opened, minute, released, per_minute, path):
if minute < 26 and (minute < 10 or released > 220) and (minute < 15 or released > 720) and (minute < 20 or released > 1480):
def possibilites(pos, last):
pressure, neighbors = nodes[pos]
# open the value
if pos not in opened and pressure > 0:
yield (pos, {pos, }, pressure, "drain "+pos+" ("+str(pressure)+")")
# go to neighbor
if len(opened) < len(nodes) - 1:
for name in random.sample(neighbors, len(neighbors)):
if name != last:
yield (name, set(), 0, "goto "+name)
lists = [list(possibilites(p, l)) for p, l in zip(positions, lasts)]
for nexts, opening, releasing, actions in (list(zip(*x)) for x in itertools.product(*lists)):
if len(set().union(*opening)) == sum(len(o) for o in opening):
yield from solve(nexts, positions, opened.union(*opening), minute+1, released+per_minute, per_minute+sum(releasing), [*path, (actions, minute, released, per_minute)])
# finish
if minute > 20:
yield released + (26-minute+1)*per_minute, [*path, ("finish", positions, minute, released, per_minute)]
mx = 0
for val, path in solve(["AA", "AA"], [None, None], set(), 1, 0, 0, []):
if val > mx:
print(val, path)
mx = val
# 2838 [(('goto GY', 'goto XT'), 1, 0, 0), (('goto QK', 'goto KQ'), 2, 0, 0), (('drain QK (10)', 'drain KQ (17)'), 3, 0, 0), (('goto QU', 'goto OY'), 4, 0, 27), (('goto YC', 'goto EI'), 5, 27, 27), (('drain YC (9)', 'goto RF'), 6, 54, 27), (('goto DV', 'drain RF (18)'), 7, 81, 36), (('goto AI', 'goto SK'), 8, 117, 54), (('drain AI (25)', 'goto AZ'), 9, 171, 54), (('goto DV', 'drain AZ (20)'), 10, 225, 79), (('goto YC', 'goto SE'), 11, 304, 99), (('goto XH', 'goto VI'), 12, 403, 99), (('goto HC', 'drain VI (22)'), 13, 502, 99), (('drain HC (24)', 'goto JR'), 14, 601, 121), (('goto XH', 'goto PU'), 15, 722, 145), (('goto YC', 'goto IM'), 16, 867, 145), (('goto DJ', 'drain IM (19)'), 17, 1012, 145), (('goto UV', 'goto QS'), 18, 1157, 164), (('goto ZJ', 'goto IY'), 19, 1321, 164), (('drain ZJ (6)', 'drain IY (15)'), 20, 1485, 164), (('goto ME', 'goto QM'), 21, 1649, 185), (('goto BA', 'goto AQ'), 22, 1834, 185), (('goto KZ', 'drain AQ (23)'), 23, 2019, 185), (('drain KZ (5)', 'goto FA'), 24, 2204, 208), ('finish', ('KZ', 'FA'), 25, 2412, 213)]