Skip to content

Instantly share code, notes, and snippets.

@neofight78
Last active December 17, 2021 13:52
Show Gist options
  • Select an option

  • Save neofight78/81937c6332500168d03c60af80c638f5 to your computer and use it in GitHub Desktop.

Select an option

Save neofight78/81937c6332500168d03c60af80c638f5 to your computer and use it in GitHub Desktop.
Advent of Code 2021 - Day 17: Trick Shot
fn main() {
let hits = find_all_hits((128, 160, -142, -88));
let max_height = hits.iter().map(|&(_, y)| triangle(y)).max().unwrap();
let total_hits = hits.len();
println!("The highest position reached was {}.", max_height);
println!("The total number of hits was {}.", total_hits);
}
fn triangle(n: i64) -> i64 {
(n.pow(2) + n) / 2
}
fn triangle_root(n: i64) -> i64 {
(n as f64 * 2.0).sqrt() as i64
}
fn find_all_hits((min_x, max_x, min_y, max_y): (i64, i64, i64, i64)) -> Vec<(i64, i64)> {
(triangle_root(min_x)..=max_x)
.flat_map(|x| {
(min_y..-min_y)
.map(move |y| (x, y))
.filter(|&v| hits_target(v, (min_x, max_x, min_y, max_y)))
})
.collect()
}
fn hits_target(
(mut x_velocity, mut y_velocity): (i64, i64),
(min_x, max_x, min_y, max_y): (i64, i64, i64, i64),
) -> bool {
let mut x = 0;
let mut y = 0;
while y_velocity > 0 || y >= min_y {
if x >= min_x && x <= max_x && y >= min_y && y <= max_y {
return true;
}
x += x_velocity;
y += y_velocity;
x_velocity -= x_velocity.cmp(&0) as i64;
y_velocity -= 1;
}
false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment