From c449b002f8821cb9f6d81ff2051914beb72bf541 Mon Sep 17 00:00:00 2001 From: BoolPurist Date: Fri, 30 Aug 2024 03:06:53 +0200 Subject: [PATCH] Made solution for day 6 faster --- crates/solutions/src/day6.rs | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/solutions/src/day6.rs b/crates/solutions/src/day6.rs index bd51482..089bf95 100644 --- a/crates/solutions/src/day6.rs +++ b/crates/solutions/src/day6.rs @@ -1,3 +1,5 @@ +use std::usize; + mod parsing; mod race_record; @@ -16,11 +18,34 @@ pub fn solve_task_1(input: &str) -> String { } pub fn solve_task_2(input: &str) -> String { let parsed = parsing::parsing_part_2(input); - let how_many_times_won = all_rounds_of_durations(parsed.time()) + + let time_to_beat = parsed.time(); + assert!(time_to_beat > 1, "Race time must be at least 2"); + const FIRST_AND_LAST_CYCLE_DO_NOT_MOVE: NumericValue = 2; + const HALF_AT_OR_OVER_PEAK: NumericValue = 2; + let range: NumericValue = + (parsed.time() - FIRST_AND_LAST_CYCLE_DO_NOT_MOVE) / HALF_AT_OR_OVER_PEAK; + + const FIRST_CYCLE_NO_DISTANCE: usize = 1; + for (index, next_distance) in all_rounds_of_durations(parsed.time()) .into_iter() - .filter(|&distance| distance > parsed.reached_distance()) - .count() as NumericValue; - how_many_times_won.to_string() + .enumerate() + .skip(FIRST_CYCLE_NO_DISTANCE) + { + if next_distance > parsed.reached_distance() { + const EVEN_TIME_TO_BEAT_LEADS_UNEVEN_PICK: NumericValue = 1; + let one_offset = if time_to_beat % 2 == 0 { + EVEN_TIME_TO_BEAT_LEADS_UNEVEN_PICK + } else { + 0 + }; + let lower_than_distance_over_pick = (index as NumericValue) - 1; + let both_halves = (range - lower_than_distance_over_pick) * 2; + let how_many_times_won = both_halves + one_offset; + return how_many_times_won.to_string(); + } + } + unreachable!(); } fn all_rounds_of_durations(duration: NumericValue) -> Vec {