Add day 6 part 2

master
parent cd667e4031
commit f007bee168
  1. 57
      src/day6.rs
  2. 2
      src/main.rs

@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet};
type Tree = HashMap<String, HashSet<String>>;
fn parse_input<F: BufRead> (input: &mut F) -> Tree {
fn parse_input_part1<F: BufRead> (input: &mut F) -> Tree {
let it = input.lines()
.filter_map(|line| line.ok())
.map(|line| {
@ -29,10 +29,42 @@ fn compute_checksum(tree: &Tree, root: &str, level: usize) -> usize {
}
pub fn part1<F: BufRead> (mut input: F) {
let tree = parse_input(&mut input);
let tree = parse_input_part1(&mut input);
println!("{:?}", compute_checksum(&tree, "COM", 0));
}
fn parse_input_part2<F: BufRead> (input: F) -> HashMap<String, String>{
input.lines()
.filter_map(|line| line.ok())
.map(|line| {
let v: Vec<_> = line.split(')').collect();
(v[1].to_string(), v[0].to_string())
})
.collect()
}
fn path_to_node(haystack: &HashMap<String, String>, needle: &str, start: &str) -> HashSet<String> {
let mut current = start;
let mut path = HashSet::new();
while current != needle {
current = &haystack[current];
path.insert(current.to_string());
}
path
}
fn compute_min_hop_from_you_to_santa(invert_tree: HashMap<String, String>) -> usize {
let path_from_you = path_to_node(&invert_tree, "COM", "YOU");
let path_from_santa = path_to_node(&invert_tree, "COM", "SAN");
path_from_you.symmetric_difference(&path_from_santa).collect::<HashSet<_>>().len()
}
pub fn part2<F: BufRead> (mut input: F) {
let invert_tree = parse_input_part2(&mut input);
let res = compute_min_hop_from_you_to_santa(invert_tree);
println!("{}", res);
}
#[cfg(test)]
mod test {
use super::*;
@ -51,7 +83,26 @@ D)I
E)J
J)K
K)L"#);
let tree = parse_input(&mut input);
let tree = parse_input_part1(&mut input);
assert_eq!(42, compute_checksum(&tree, "COM", 0));
}
#[test]
fn test_compute_min_hop_from_you_to_santa() {
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
K)YOU
I)SAN"#);
let invert_tree = parse_input_part2(&mut input);
assert_eq!(4, compute_min_hop_from_you_to_santa(invert_tree));
}
}

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

Loading…
Cancel
Save