Unable to load image

Day 21 AoC: use Z3 b-words

Post code, boast about it.

13
Jump in the discussion.

No email address required.

Could probably be a lot more eloquent, but tree operations are always fun. Solutions to both parts are printed near-instantly.


foo = []
with open('day21_input.txt', 'r') as inp:
    foo = inp.read().split('\n')

class Monke:
    def __init__(self, val, children):
        self.val = val
        self.children = children

monkes = {}
root_node, human_node = None, None

for f in foo:
    f, monke = f.split(' '), None
    if len(f) == 2:
        monke = Monke(int(f[1]), [])
    else:
        monke = Monke(f[2], [f[1], f[3]])
    monkes[f[0][:-1]] = monke
    if f[0][:-1] == 'root':
        root_node = monke
    if f[0][:-1] == 'humn':
        human_node = monke

def monke_find(monke, val):
    if len(monke.children) == 0:
        return False
    if val in monke.children:
        return True
    return (monke_find(monkes[monke.children[0]], val) or monke_find(monkes[monke.children[1]], val))

op = {'+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: x / y}
def monke_op(monke):
    if monke.val not in ['+', '-', '*', '/']:
        return monke.val
    result = op[monke.val](monke_op(monkes[monke.children[0]]), monke_op(monkes[monke.children[1]]))
    if not monke_find(monke, 'humn'):
        monke.val = result
    return result

def monke_eq(monke, val):
    if human_node == monke:
        return val
    n, next_step, result = None, None, None
    if monkes[monke.children[0]].val not in ['+', '-', '*', '/']:
        n, next_step = monkes[monke.children[0]].val, monkes[monke.children[1]]
    else:
        n, next_step = monkes[monke.children[1]].val, monkes[monke.children[0]]
    if monke.val == '+':
        result = val - n
    elif monke.val == '*':
        result = val / n
    elif monke.val == '-':
        if monkes[monke.children[0]].val == n:
            result = n - val
        else:
            result = n + val
    elif monke.val == '/':
        if monkes[monke.children[0]].val == n:
            result = val / n
        else:
            result = val * n
    return monke_eq(next_step, result)

print(monke_op(root_node))
human_node.val = '*'
if monke_find(monkes[root_node.children[0]], 'humn'):
    print(monke_eq(monkes[root_node.children[0]], monkes[root_node.children[1]].val))
else:
    print(monke_eq(monkes[root_node.children[1]], monkes[root_node.children[0]].val))

Jump in the discussion.

No email address required.

look im gunna have 2 ask u 2 keep ur giant dumps in the potty not in my replys 😷😷😷

Jump in the discussion.

No email address required.



Now playing: Donkey Kong December National Anthem.mp3

Link copied to clipboard
Action successful!
Error, please refresh the page and try again.