@@ 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::<isize>(include_str!("../data/day07.txt"), ',').unwrap();
+ let mut data = parse_by_char::<isize>(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::<isize>(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::<isize>(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::<isize>(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::<isize>(include_str!("../data/day07.txt"), ',').unwrap();
+ assert_eq!(find_cheapest_location(&mut data, true), 344138);
+ assert_eq!(find_cheapest_location(&mut data, false), 94862124);
}
}