r/adventofcode • • Dec 06 '23

Help/Question - RESOLVED [2023 Day 06] Stable Math Solution?

I solved this day the 0-8-15 way with an optimization for part 2 that starts on half of the available time and then searches for the max time where I break the record. The result can be doubled and subtract 1 for even times, 2 for odd times

After finishing I realized this could be solved using a simple quadratic formula or so I thought. I tried some variants but there seem to be many edge cases where the formula `sqrt(t*t - 4*d)` breaks. They often fail miserably on part 1, some also on part two for the sample input.

So my question is - can anyone provide a math solution that works on both parts for the sample and the user input?

6 Upvotes

37 comments sorted by

View all comments

Show parent comment

1

u/Symbroson Dec 06 '23 edited Dec 06 '23

Your suggestion seems to work so far. In python code it would look something like this:[Edit] updated according to u/shillbert's suggestion

def solve(t, d):
    x1 = (t - sqrt(t**2 - 4*d))/2
    x2 = (t + sqrt(t**2 - 4*d))/2
    return ceil(x2) - floor(x1) - 1

Can anyone else try this for their inputs to confirm?

3

u/bdaene Dec 06 '23 edited Dec 06 '23

I came to the same formula and it worked like a charm:

fn get_number_of_ways(time: u32, distance: u64) -> u32 {
   let t2 = (time /2) as f64;
   let d = distance as f64;
   let delta = (t2.powf(2.) - d).powf(0.5);
   let left = (t2 - delta + 1.).floor() as u32;
   let right = (t2 + delta - 1.).ceil() as u32;
   right - left + 1
}