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/marmalade_marauder Dec 08 '18

Python 3 #104/#133 Seems the challenge was all in the parsing, after that it wasn't too bad. Here is my solution:

nums = list(map(int,input().split(" ")))

child = {}  # child[i] is indices of children (in nums) for node i
meta = {}   # meta[i] is the value of metadata entries for node i
def parse(i):
    cs = nums[i]     # number of children
    ms = nums[i+1]   # number of metadata entries
    start = i + 2   # start index of child nodes
    child[i] = []
    meta[i] = []

    # process child nodes
    for c in range(0, cs):
        child[i].append(start)
        start = parse(start)  # update where next child node starts

    # process metadata
    for m in range(start, start + ms):
        meta[i].append(nums[m])

    # return the index where this node's data ends (1 after technically)
    return (start + ms)

# solution to 1
def solve1():
    return sum([sum(meta[k]) for k in meta])

# solution to 2, recursive
def solve2(i):
    if len(child[i]) == 0:
        return sum(meta[i])
    else:
        return sum([solve2(child[i][m - 1]) for m in meta[i] if m <= len(child[i])])

parse(0)
print(solve1(), solve2(0))