Commit 1f30169c authored by Jonathan Klimt's avatar Jonathan Klimt

Part 2 of day 8

parent 62375224
......@@ -9,7 +9,7 @@ struct Node {
children: Vec<usize>,
}
fn add_node(n: &mut Vec<Node>, inp: &Vec<usize>) -> usize {
fn add_node(n_vec: &mut Vec<Node>, inp: &Vec<usize>) -> usize {
// println!("Input: {:?}", inp);
let mut new_node: Node = Node::default();
let nr_children = inp[0];
......@@ -19,23 +19,42 @@ fn add_node(n: &mut Vec<Node>, inp: &Vec<usize>) -> usize {
for i in 2..2 + nr_metadata {
new_node.metadata.push(inp[i]);
}
n.push(new_node);
n_vec.push(new_node);
return nr_metadata + 2;
}
let mut payload_index = 2;
let mut payload_index = 2; // skip child count/metadata count
// create child nodes
for _ in 0..nr_children {
let smaller_input: Vec<usize> = inp[payload_index..].to_vec();
payload_index += add_node(n, &smaller_input);
payload_index += add_node(n_vec, &smaller_input);
new_node.children.push(n_vec.len() - 1);
}
// after all childs are done, the payload comes
for i in payload_index..payload_index + nr_metadata {
new_node.metadata.push(inp[i]);
payload_index += 1;
}
n.push(new_node);
n_vec.push(new_node);
payload_index
}
fn get_value_part2(n_vec: &Vec<Node>, n_index: usize) -> Result<usize, Error> {
let cur_node: &Node = &n_vec[n_index];
if cur_node.children.len() == 0 {
return Ok(cur_node.metadata.iter().sum());
}
let mut sum = 0;
for i in &cur_node.metadata {
if let Some(childnode_id) = cur_node.children.get(*i - 1) {
sum += get_value_part2(n_vec, *childnode_id)?;
}
}
Ok(sum)
}
fn main() -> Result<(), Error> {
let f = fs::read_to_string("input.txt")?;
......@@ -48,12 +67,17 @@ fn main() -> Result<(), Error> {
inp_vec.append(&mut tmp_inp_vec);
}
add_node(&mut node_vec, &inp_vec);
// calculate part 1
let sum = node_vec
.clone()
.into_iter()
.map(|n| n.metadata)
.flatten()
.sum::<usize>();
println!("Sum: {:?}", sum);
println!("Part 1 - Sum: {:?}", sum);
let sum2 = get_value_part2(&node_vec, node_vec.len() - 1);
println!("Part 2 - Sum: {:?}", sum2?);
Ok(())
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment