From 3f74dcb73e7d1aa17790784616e23a1ea4ee6886 Mon Sep 17 00:00:00 2001 From: Tyler Hallada Date: Mon, 17 Dec 2018 23:34:54 -0500 Subject: [PATCH] Day 4 part 2 It passes the tests but the real solution is incorrect :( --- src/day4.rs | 25 +++++++++++++++++++++++++ src/main.rs | 1 + 2 files changed, 26 insertions(+) diff --git a/src/day4.rs b/src/day4.rs index 82f998a..c25536f 100644 --- a/src/day4.rs +++ b/src/day4.rs @@ -65,6 +65,10 @@ pub fn solve_part1() -> Result> { Ok(get_part1(INPUT)?) } +pub fn solve_part2() -> Result> { + Ok(get_part2(INPUT)?) +} + fn get_part1(filename: &str) -> Result> { let records = read_records(filename)?; let minutes_asleep = minutes_asleep_per_guard(records); @@ -73,6 +77,22 @@ fn get_part1(filename: &str) -> Result> { Ok(sleepiest_guard.0 * sleepiest_minute) } +fn get_part2(filename: &str) -> Result> { + let records = read_records(filename)?; + let minutes_asleep = minutes_asleep_per_guard(records); + let all_mins: Vec = minutes_asleep + .values() + .flat_map(|mins| mins.iter()) + .cloned() + .collect(); + let sleepiest_minute = mode(&all_mins[..]); + let sleepiest_guard = minutes_asleep + .iter() + .max_by_key(|(_, mins)| mins.into_iter().filter(|min| **min == sleepiest_minute).count()) + .unwrap(); + Ok(sleepiest_guard.0 * sleepiest_minute) +} + fn mode(numbers: &[u32]) -> u32 { let mut occurences = HashMap::new(); for &value in numbers { @@ -283,4 +303,9 @@ mod tests { fn solves_part1() { assert_eq!(get_part1(TEST_INPUT).unwrap(), 240); } + + #[test] + fn solves_part2() { + assert_eq!(get_part2(TEST_INPUT).unwrap(), 4455); + } } diff --git a/src/main.rs b/src/main.rs index 43eba14..3694610 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,4 +15,5 @@ fn main() { println!("{}", day3::solve_part2().unwrap().unwrap()); println!("Day 4:"); println!("{}", day4::solve_part1().unwrap()); + println!("{}", day4::solve_part2().unwrap()); }