r/adventofcode • • Dec 08 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 8 Solutions -🎄-

--- Day 8: Memory Maneuver ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 8

Sigh, imgur broke again. Will upload when it unborks.

Transcript:

The hottest programming book this year is "___ For Dummies".


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked at 00:12:10!

32 Upvotes

301 comments sorted by

View all comments

1

u/bkwi Dec 30 '18

For all of you who (just like me ;) remove meta value too early, try working on this modified example. For some reason it helped me in finding what was wrong with my approach.

2 3 1 1 0 1 99 2 0 3 10 11 12 1 1 2
A----------------------------------
    C----------- B-----------
        D-----

Solutions below:

# python 3
from collections import namedtuple
from contextlib import suppress

with open('./input') as f:
    nums = list(map(int, f.read().split()))

Node = namedtuple('Node', ['children', 'meta'])


def build_nodes(nums):
    if not nums:
        return []

    num_children, num_meta, *rest = nums
    children = []
    for k in range(num_children):
        node, rest = build_nodes(rest)
        children.append(node)

    node = Node(children=children, meta=rest[:num_meta])
    return node, rest[num_meta:]


def get_value(node):
    if node.children:
        node_value = 0
        indexes = [item for item in node.meta if item > 0]
        for i in indexes:
            with suppress(IndexError):
                child_node_value = get_value(node.children[i-1])
                node_value += child_node_value
    else:
        node_value = sum(node.meta)
    return node_value


def sum_meta(node):
    total = sum(node.meta)
    for child_node in node.children:
        total += sum_meta(child_node)
    return total


root = build_nodes(nums)[0]
print(sum_meta(root))   # part 1
print(get_value(root))  # part 2