Skip to content
advent of code 2023

day 19

aplenty

approach

workflows are parsed into a dict from name to a list of rule strings. the ratings are turned into dict literals with a few string replacements and eval, and part 1 evaluates each condition with eval using the part as the namespace, following workflows until it reaches A or R. the accepted parts' ratings are summed.

part 2 does a dfs from in, keeping a list of the conditions on the current path. for each rule it recurses with the condition added, then replaces it with its negation (> becomes <=, < becomes >=) before moving on to the next rule. at A, count_paths turns the list into a min and max per category within 1..4000 and multiplies the widths.

the trick

carry the conditions down the dfs and negate each one for the rules after it; at A the ranges multiply out.

python
cond, nxt = rule.split(":")
if ">" in cond:
    path.append(cond)
    res += dfs(wfs, nxt, path)
    path.pop()
    unwind += 1
    path.append(cond.replace(">", "<="))
else:
    path.append(cond)
    res += dfs(wfs, nxt, path)
    path.pop()
    unwind += 1
    path.append(cond.replace("<", ">="))