From b283c88975c08a554c67dd1e4bc5716b9d3d401f Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Wed, 8 Dec 2021 21:09:08 -0700 Subject: [PATCH] day 7 optimizations - no need to sort thanks to `select_nth_unstable()` - don't copy the array around --- src/day07.rs | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/day07.rs b/src/day07.rs index 651c9bc..36a5e6d 100644 --- a/src/day07.rs +++ b/src/day07.rs @@ -2,10 +2,10 @@ use anyhow::Result; use crate::utils::parse_by_char; -fn get_median(positions: &[isize]) -> isize { - let mut sorted_pos = positions.to_owned(); - sorted_pos.sort_unstable(); - sorted_pos[sorted_pos.len() / 2] +fn get_median(positions: &mut [isize]) -> isize { + let median_index = positions.len() / 2; + positions.select_nth_unstable(median_index); // quickselect in the standard library! + positions[median_index] } fn compute_fuel(positions: &[isize], target: isize, cheap_fuel: bool) -> usize { @@ -22,7 +22,7 @@ fn compute_fuel(positions: &[isize], target: isize, cheap_fuel: bool) -> usize { .sum() } -fn find_cheapest_location(positions: &[isize], cheap_fuel: bool) -> usize { +fn find_cheapest_location(positions: &mut [isize], cheap_fuel: bool) -> usize { // find start point let start = get_median(positions); let mut position = start; @@ -56,10 +56,10 @@ fn find_cheapest_location(positions: &[isize], cheap_fuel: bool) -> usize { } pub(crate) fn run() -> Result<(usize, usize)> { - let data = parse_by_char::(include_str!("../data/day07.txt"), ',').unwrap(); + let mut data = parse_by_char::(include_str!("../data/day07.txt"), ',').unwrap(); Ok(( - find_cheapest_location(&data, true), - find_cheapest_location(&data, false), + find_cheapest_location(&mut data, true), + find_cheapest_location(&mut data, false), )) } @@ -69,15 +69,15 @@ mod tests { #[test] fn test_example() { - let data = parse_by_char::(include_str!("../data/day07-test.txt"), ',').unwrap(); - assert_eq!(find_cheapest_location(&data, true), 37); - assert_eq!(find_cheapest_location(&data, false), 168); + let mut data = parse_by_char::(include_str!("../data/day07-test.txt"), ',').unwrap(); + assert_eq!(find_cheapest_location(&mut data, true), 37); + assert_eq!(find_cheapest_location(&mut data, false), 168); } #[test] fn test_my_data() { - let data = parse_by_char::(include_str!("../data/day07.txt"), ',').unwrap(); - assert_eq!(find_cheapest_location(&data, true), 344138); - assert_eq!(find_cheapest_location(&data, false), 94862124); + let mut data = parse_by_char::(include_str!("../data/day07.txt"), ',').unwrap(); + assert_eq!(find_cheapest_location(&mut data, true), 344138); + assert_eq!(find_cheapest_location(&mut data, false), 94862124); } } -- 2.45.2