Last active
December 9, 2018 11:59
-
-
Save qubyte/0999990ccf96cbb34a8493f90a5a0c64 to your computer and use it in GitHub Desktop.
Advent of Code 2018 day 8 task 2.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io::{self, BufRead}; | |
use std::str; | |
struct Node { | |
children: Vec<Box<Node>>, | |
metadata: Vec<usize> | |
} | |
impl Node { | |
fn evaluate(&self) -> usize { | |
match self.children.len() { | |
0 => self.metadata.iter().sum(), | |
_ => self.metadata.iter().filter_map(|&i| { | |
let is_valid_index = i > 0 && i <= self.children.len(); | |
if is_valid_index { | |
Some(self.children[i - 1].evaluate()) | |
} else { | |
None | |
} | |
}).sum() | |
} | |
} | |
fn compile_tree(numbers: Vec<usize>) -> Node { | |
let (_num_meta, node) = read_node(&numbers[..]); | |
node | |
} | |
} | |
fn read_node(numbers: &[usize]) -> (usize, Node) { | |
let num_children = numbers[0]; | |
let num_meta = numbers[1]; | |
let mut offset = 2; | |
let mut children = Vec::new(); | |
for _i in 0..num_children { | |
let (size, child) = read_node(&numbers[offset..]); | |
children.push(Box::new(child)); | |
offset += size; | |
} | |
let metadata = numbers[offset..(num_meta + offset)].to_vec(); | |
(num_meta + offset, Node { children, metadata }) | |
} | |
fn main() { | |
let stdin = io::stdin(); | |
let numbers: Vec<usize> = stdin | |
.lock() | |
.split(b' ') | |
.filter_map(|bytes| { | |
if let Ok(by) = bytes { | |
let b = by.to_vec(); | |
let s = str::from_utf8(&b).unwrap().trim(); | |
if s.is_empty() { | |
None | |
} else { | |
Some(s.parse().unwrap()) | |
} | |
} else { | |
None | |
} | |
}) | |
.collect(); | |
println!("{}", Node::compile_tree(numbers).evaluate()); | |
} |
Author
qubyte
commented
Dec 8, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment