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

For the sample input your part 1 returns 352 when it should be 288

3

u/MagiMas Dec 06 '23 edited Dec 06 '23

Yeah you're right. Because I was stupid and optimized my code after completion and during optimization removed the boundary checks without rechecking with the test input.

The problem arises when lower_bound or upper_bound already are integers before applying the floor or ceiling functions and the strict greater than condition.

You just need to add a check before the ceil and floor functions and add/subtract 1s respectively.

1

u/DarkLord76865 Dec 06 '23

Well you got lucky then since one of my inputs produced integer roots. But yeah, simple if check solves the problem.

1

u/MagiMas Dec 06 '23

Updated the code with a working version

2

u/Symbroson Dec 06 '23

nice! Seems to match with u/DeepDay6's suggestion