re: AoC Day 8: Memory Maneuver VIEW POST

FULL DISCUSSION
 

Here is my Python Solution:

Both parts

with open("input.txt") as f:
    numbers = [int(x) for x in next(f).split()]

class Node(object):
    def __init__(self, n_childs, n_metadata):
        self.n_childs = n_childs
        self.n_metadata = n_metadata
        self.childs = []
        self.metadata = []

it = iter(numbers)
root = Node(next(it), next(it))

stack = []
for _ in range(root.n_metadata):
    stack.append(("metadata", root))
for _ in range(root.n_childs):
    stack.append(("childs", root))

while stack:
    inst, current = stack.pop()
    if inst == "childs":
        new_node = Node(next(it), next(it))
        current.childs.append(new_node)
        for _ in range(new_node.n_metadata):
            stack.append(("metadata", new_node))
        for _ in range(new_node.n_childs):
            stack.append(("childs", new_node))
    else:
        current.metadata.append(next(it))

Part 1

def tree_sum(n):
    return sum(n.metadata)+sum(tree_sum(c) for c in n.childs)

print(tree_sum(root))

Part 2

def tree_sum2(n):
    if len(n.childs) == 0:
        return sum(n.metadata)
    else:
        d = dict((i+1, c) for i, c in enumerate(n.childs))
        return sum(tree_sum2(d.get(m, Node(0,0))) for m in n.metadata)

print(tree_sum2(root))
code of conduct - report abuse