Add day 6 part 1

master
parent 4596b08f56
commit cd667e4031
  1. 1294
      input/day6
  2. 57
      src/day6.rs
  3. 3
      src/main.rs

File diff suppressed because it is too large Load Diff

@ -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));
}
}

@ -12,6 +12,8 @@ mod day2;
mod day3;
mod day4;
mod day5;
mod day6;
mod intcode;
fn main() {
@ -47,6 +49,7 @@ fn main() {
day3::part1, day3::part2,
day4::part1, day4::part2,
day5::part1, day5::part1,
day6::part1,
];
if let Some(f) = challenges.get(challenge) {

Loading…
Cancel
Save