3 changed files with 1354 additions and 0 deletions
File diff suppressed because it is too large
@ -0,0 +1,57 @@ |
|||
use std::io::BufRead; |
|||
use std::collections::{HashMap, HashSet}; |
|||
|
|||
type Tree = HashMap<String, HashSet<String>>; |
|||
|
|||
fn parse_input<F: BufRead> (input: &mut F) -> Tree { |
|||
let it = input.lines() |
|||
.filter_map(|line| line.ok()) |
|||
.map(|line| { |
|||
let v: Vec<_> = line.split(')').collect(); |
|||
(v[0].to_string(), v[1].to_string()) |
|||
}); |
|||
let mut tree = HashMap::new(); |
|||
for (parent, child) in it { |
|||
let children = tree.entry(parent).or_insert(HashSet::new()); |
|||
children.insert(child); |
|||
} |
|||
tree |
|||
} |
|||
|
|||
fn compute_checksum(tree: &Tree, root: &str, level: usize) -> usize { |
|||
if let Some(children) = tree.get(root) { |
|||
level + children.iter() |
|||
.map(|child| compute_checksum(&tree, child, level + 1)) |
|||
.sum::<usize>() |
|||
} else { |
|||
level |
|||
} |
|||
} |
|||
|
|||
pub fn part1<F: BufRead> (mut input: F) { |
|||
let tree = parse_input(&mut input); |
|||
println!("{:?}", compute_checksum(&tree, "COM", 0)); |
|||
} |
|||
|
|||
#[cfg(test)] |
|||
mod test { |
|||
use super::*; |
|||
use std::io; |
|||
|
|||
#[test] |
|||
fn test_compute_checksum() { |
|||
let mut input = io::Cursor::new(r#"COM)B |
|||
B)C |
|||
C)D |
|||
D)E |
|||
E)F |
|||
B)G |
|||
G)H |
|||
D)I |
|||
E)J |
|||
J)K |
|||
K)L"#); |
|||
let tree = parse_input(&mut input); |
|||
assert_eq!(42, compute_checksum(&tree, "COM", 0)); |
|||
} |
|||
} |
Loading…
Reference in new issue