diff --git a/2023/data/day6.txt b/2023/data/day6.txt new file mode 100644 index 0000000..be69c19 --- /dev/null +++ b/2023/data/day6.txt @@ -0,0 +1,2 @@ +Time: 44 82 69 81 +Distance: 202 1076 1138 1458 diff --git a/2023/src/day6.rs b/2023/src/day6.rs new file mode 100644 index 0000000..2c5a8d3 --- /dev/null +++ b/2023/src/day6.rs @@ -0,0 +1,44 @@ +const RACES: [(u64, u64); 4] = [(44, 202), (82, 1076), (69, 1138), (81, 1458)]; + +pub fn day6a() -> String { + let score = RACES + .iter() + .map(|(time, winning_distance)| optimal_winners(*time, *winning_distance).len()) + .fold(1, |acc, val| acc * val); + format!("{}", score) +} + +pub fn day6b() -> String { + format!("{}", optimal_winners(44826981, 202107611381458).len()) +} + +fn optimal_winners(total_time: u64, winning_distance: u64) -> Vec { + race_distances(total_time) + .filter(|(_, distance)| *distance > winning_distance) + .map(|(time, _)| time) + .collect::>() +} + +fn race_distances(total_time: u64) -> impl Iterator { + (0..total_time) + .map(move |charge_time| (charge_time, distance(charge_time, total_time - charge_time))) +} + +fn distance(charge_time: u64, remaining_time: u64) -> u64 { + charge_time * remaining_time +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_winners() { + assert_eq!(optimal_winners(7, 9), vec![2, 3, 4, 5]); + assert_eq!(optimal_winners(15, 40), vec![4, 5, 6, 7, 8, 9, 10, 11]); + assert_eq!( + optimal_winners(30, 200), + vec![11, 12, 13, 14, 15, 16, 17, 18, 19] + ); + } +} diff --git a/2023/src/main.rs b/2023/src/main.rs index dacd074..f33a2d8 100644 --- a/2023/src/main.rs +++ b/2023/src/main.rs @@ -3,6 +3,7 @@ mod day2; mod day3; mod day4; mod day5; +mod day6; fn main() { let day = std::env::args().skip(1).next(); @@ -18,6 +19,8 @@ fn main() { Some("4b") => day4::day4b(), Some("5a") => day5::day5a(), Some("5b") => day5::day5b(), + Some("6a") => day6::day6a(), + Some("6b") => day6::day6b(), _ => panic!("unrecognized day"), };