AoC21/src/day17.rs

41 lines
1.0 KiB
Rust

use std::cmp::max;
use std::ops::RangeInclusive;
pub fn day17() {
solve(&(20..=30), &(-10..=-5));
solve(&(287..=309), &(-76..=-48));
}
fn solve(target_x: &RangeInclusive<isize>, target_y: &RangeInclusive<isize>) {
let maxes = (0..=*target_x.end()).flat_map(|vx| {
(*target_y.start()..=100).filter_map(move |vy| count_steps(vx, vy, target_x, target_y))
});
dbg!(maxes.clone().max());
dbg!(maxes.count());
}
fn count_steps(
mut vx: isize,
mut vy: isize,
target_x: &RangeInclusive<isize>,
target_y: &RangeInclusive<isize>,
) -> Option<isize> {
let mut x = 0;
let mut y = 0;
let mut max_y = 0;
loop {
x += vx;
y += vy;
vx -= vx.signum();
vy -= 1;
max_y = max(max_y, y);
if target_x.contains(&x) && target_y.contains(&y) {
return Some(max_y);
} else if !target_x.contains(&x) && vx == 0 {
return None;
} else if !target_y.contains(&y) && y < *target_y.start() {
return None;
}
}
}