aoc/year2018/
day08.rs

1//! # Memory Maneuver
2//!
3//! Recursive solution computing both parts at the same time, sharing a single mutable iterator.
4//! A shared stack is used to store the scores for child nodes temporarily.
5use crate::util::parse::*;
6
7type Input = (usize, usize);
8
9pub fn parse(input: &str) -> Input {
10    parse_node(&mut input.iter_unsigned(), &mut Vec::new())
11}
12
13pub fn part1(input: &Input) -> usize {
14    input.0
15}
16
17pub fn part2(input: &Input) -> usize {
18    input.1
19}
20
21fn parse_node(iter: &mut impl Iterator<Item = usize>, stack: &mut Vec<usize>) -> (usize, usize) {
22    // Parse header
23    let child_count = iter.next().unwrap();
24    let metadata_count = iter.next().unwrap();
25
26    let mut metadata = 0;
27    let mut score = 0;
28
29    // Parse child nodes, adding their metadata to current node and saving their score for
30    // when metadata is processed.
31    for _ in 0..child_count {
32        let (first, second) = parse_node(iter, stack);
33        metadata += first;
34        stack.push(second);
35    }
36
37    // Process metadata.
38    for _ in 0..metadata_count {
39        let n = iter.next().unwrap();
40        metadata += n;
41
42        if child_count == 0 {
43            score += n;
44        } else if n > 0 && n <= child_count {
45            score += stack[stack.len() - child_count + (n - 1)];
46        }
47    }
48
49    // Pop child nodes from the stack.
50    stack.truncate(stack.len() - child_count);
51
52    (metadata, score)
53}