AoC21/src/day07.rs

45 lines
1.2 KiB
Rust

pub fn day7() {
// let input = "16,1,2,0,4,2,7,1,2,14";
let input = include_str!("../input/day7.txt");
let horiz_positions = input
.trim()
.split(",")
.map(|s| s.parse::<i32>().unwrap())
.collect::<Vec<_>>();
let candidates =
*horiz_positions.iter().min().unwrap()..=*horiz_positions.iter().max().unwrap();
let min = candidates
.clone()
.min_by_key(|pos| cost_to_align_at(pos, &horiz_positions));
println!("target position: {:?}", min);
println!(
"fuel cost: {:?}",
cost_to_align_at(&min.unwrap(), &horiz_positions)
);
let p2_min = candidates.min_by_key(|pos| p2_cost(pos, &horiz_positions));
println!("p2 target position: {:?}", p2_min);
println!(
"p2 fuel cost: {:?}",
p2_cost(&p2_min.unwrap(), &horiz_positions)
);
}
fn cost_to_align_at(target: &i32, horiz_positions: &[i32]) -> i32 {
horiz_positions.iter().map(|pos| (pos - target).abs()).sum()
}
fn p2_cost(target: &i32, horiz_positions: &[i32]) -> i32 {
horiz_positions
.iter()
.map(|pos| {
let max = (pos - target).abs();
// thanks, Gauss
(max * (max + 1)) / 2
})
.sum()
}