timvisee/advent-of-code-2021

Day17a runtime improvements

pevers opened this issue · 1 comments

Thanks for your work!

One suggestion for day17a is to directly calculate the answer instead of "firing" a shot. The probe will hit the x-axis with a velocity of -by (start velocity). So in the next step it should not overshoot, therefore n(n+1)/2 = -(min(by))-1

fn main() {
    let input = "target area: x=269..292, y=-68..-44";
    let bounds: (i32, i32) = input[13..]
        .split_once(", ")
        .and_then(|(_,by)| {
            let (y, yy) = by.split_once("..").unwrap();
            Some((y[2..].parse::<i32>().unwrap(), yy.parse::<i32>().unwrap()))
        })
        .unwrap();
    // Solve n(n+1)/2 where n = -(min(by)) - 1
    let n = -bounds.0.min(bounds.1) - 1;
    println!("{}", (n*(n+1))/2);
}

This is brilliant! Very well done. Thanks so much for sharing this.