summaryrefslogtreecommitdiffstats
path: root/21.py
blob: 1a44a55321a07dcc5fc5c98f3c21cacf6886a425 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from functools import cache
from operator import add, sub, mul, truediv, eq
from subprocess import run, PIPE
from utils import open_day
from z3 import Int, ArithRef, solve

monkeys = {}
with open_day(21) as f:
    for line in f:
        target, expr = line.rstrip().split(': ')
        expr = expr.split(' ')
        if len(expr) == 1:
            expr = int(expr[0])
        monkeys[target] = expr

ops = { '+': add, '-': sub, '*': mul, '/': truediv, '==': eq }

def eval_monkey(m):
    expr = monkeys[m]
    if isinstance(expr, int) or isinstance(expr, ArithRef):
        return expr
    return ops[expr[1]](eval_monkey(expr[0]), eval_monkey(expr[2]))

print(int(eval_monkey('root')))
monkeys['humn'] = Int('humn')
monkeys['root'][1] = '=='
solve(eval_monkey('root'))