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!

31 Upvotes

301 comments sorted by

View all comments

1

u/Voltasalt Dec 09 '18

Rust (didn't go for leaderboard). I have a runner wrapper that runs part1() and part2() and passes the 2nd tuple item of part1()'s return value as part2()'s second parameter, to "pass-through" internal state without some sort of global storage.

#[derive(Debug)]
pub struct Node {
    child_nodes: Vec<Node>,
    metadata: Vec<usize>
}

fn parse_node(i: &mut impl Iterator<Item=usize>) -> Node {
    let nodes = i.next().unwrap();
    let metadatas = i.next().unwrap();
    
    let child_nodes = (0..nodes).map(|_| parse_node(i)).collect();
    let metadata = (0..metadatas).map(|_| i.next().unwrap()).collect();

    Node {
        child_nodes, metadata
    }
}

fn sum_metadata(node: &Node) -> usize {
    node.metadata.iter().sum::<usize>() + node.child_nodes.iter().map(sum_metadata).sum::<usize>()
}

fn value(node: &Node) -> usize {
    if node.child_nodes.len() == 0 {
        sum_metadata(node)
    } else {
        node.metadata
            .iter()
            .flat_map(|idx| node.child_nodes.get(idx - 1))
            .map(value)
            .sum()
    }
}

pub fn part1(input: &str) -> (String, Node) {
    let mut iter = input
        .split(" ")
        .map(|c| c.trim().parse::<usize>().unwrap());
    
    let root = parse_node(&mut iter);
    (sum_metadata(&root).to_string(), root)
}

pub fn part2(_: &str, root: Node) -> String {
    value(&root).to_string()
}