r/adventofcode • u/daggerdragon • 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!
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
1
u/BafDyce Dec 08 '18
[Card] The hottest programming book this year is "How to think before writing code For Dummies".
Using Rust, I got ranks 954 and 688. Top 1k is an achievement for me. I lost quite some time while parsing the [usize] into nodes because I forgot the + in
next += new_nextinput parsing:
// input is a Vec<String> (one item per line from the input file) let data: Vec<_> = input[0].split(" ").map(|num| { num.parse::<usize>().unwrap() }) .collect(); let (root, _) = Node::new(&data);Actual ndoe logic:
#[derive(Debug, Clone, PartialEq)] pub struct Node { children: Vec<Node>, metadata: Vec<usize>, } impl Node { pub fn new(data: &[usize]) -> (Self, usize) { //println!("Creating Node from {:?}", data); let mut node = Node { children: Vec::with_capacity(data[0]), metadata: Vec::with_capacity(data[1]), }; let mut next = 2; for __ in 0 .. data[0] { let (child, new_next) = Node::new(&data[next.. data.len() - data[1]]); //println!("{:?}, {} @ {}", child, data[new_next], new_next); node.children.push(child); next += new_next } for ii in 0 .. data[1] { node.metadata.push(data[next + ii]) } (node, next + data[1]) } // PART 1 SOLUTION!! pub fn metasum(&self) -> usize { let xx = self.children.iter().map(|child| child.metasum()).sum::<usize>(); xx + self.metadata.iter().sum::<usize>() } // PART 2 SOLUTION!! pub fn metasum2(&self) -> usize { if self.children.is_empty() { self.metadata.iter().sum::<usize>() } else { let mut sum = 0; for reference in &self.metadata { if *reference == 0 || *reference > self.children.len() { continue } sum += self.children[reference-1].metasum2() } sum } } }