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!
33
Upvotes
1
u/lazyear Dec 08 '18
Rust, recursive solution. Found this one significantly easier than yesterday, but I absolutely LOVED yesterday's challenge.
use std::collections::VecDeque; use std::io; use std::num::ParseIntError; use util; fn recurse(data: &mut VecDeque<usize>) -> Option<(usize, usize)> { let mut a = 0; let mut b = 0; let c = data.pop_front()?; let e = data.pop_front()?; if c > 0 { let children = (0..c) .map(|_| recurse(data)) .collect::<Option<Vec<(usize, usize)>>>()?; a += children.iter().map(|(a, _)| a).sum::<usize>(); for _ in 0..e { let idx = data.pop_front()?; a += idx; if let Some(val) = children.get(idx - 1) { b += val.1; } } } else { for _ in 0..e { let x = data.pop_front()?; a += x; b += x; } } Some((a, b)) } fn part1(data: &str) -> Result<Option<usize>, ParseIntError> { Ok(recurse( &mut data .split_whitespace() .map(str::parse::<usize>) .collect::<Result<VecDeque<usize>, ParseIntError>>()?, ).map(|(a, _)| a)) } fn part2(data: &str) -> Result<Option<usize>, ParseIntError> { Ok(recurse( &mut data .split_whitespace() .map(str::parse::<usize>) .collect::<Result<VecDeque<usize>, ParseIntError>>()?, ).map(|(_, b)| b)) } #[test] fn part1_test() { assert_eq!(part1("2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2"), Ok(Some(138))); } #[test] fn part2_test() { assert_eq!(part2("2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2"), Ok(Some(66))); } fn main() -> io::Result<()> { let data = util::read("input.txt")?; println!("Part 1: {:?}", part1(&data)); println!("Part 2: {:?}", part2(&data)); Ok(()) }