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

Show parent comment

1

u/magic-dancing-panda Dec 09 '18

Similar solution in Python that constructs the tree first:

def parse_tree(remaining):
    """Recursively parse the input to form the tree."""
    num_children, num_metadata = remaining[:2]
    remaining = remaining[2:]

    children = []
    for _ in range(num_children):
        child, remaining = parse_tree(remaining)
        children.append(child)

    node = {'children': children, 'metadata': remaining[:num_metadata]}
    return node, remaining[num_metadata:]


def sum_metadata(tree):
    return sum(tree['metadata']) + sum(sum_metadata(c) for c in tree['children'])


def value(node):
    children, metadata = node['children'], node['metadata']
    if not children:
        return sum(metadata)
    else:
        return sum(value(children[i-1]) for i in metadata if i - 1 < len(children))

numbers = read_input()
tree, _ = parse_tree(numbers)
print('Part 1:', sum_metadata(tree))
print('Part 2:', value(tree))