module Problem144 where

main :: IO ()
main = print . length . takeWhile inside $ iterate reflect ((0, 10.1), (1.4, -9.6))
  where
    inside (_, (x, y)) = not $ y > 0 && -0.01 <= x && x <= 0.01
    reflect ((x1, y1), p2@(x2, y2)) = (p2, (x, y))
      where
        -- reflection
        m1 = (y2 - y1) / (x2 - x1) -- incident
        m  = y2 / (4 * x2) -- normal
        m2 = (2 * m + m * m * m1 - m1) / (2 * m1 * m - m * m + 1) --reflected
        -- intersection with ellipse, quadratic equation
        a  = m2 * m2 + 4
        b  = 2 * m2 * (y2 - m2 * x2)
        -- find next point by sum of roots
        x  = (-b / a) - x2
        y  = y2 + m2 * (x - x2)
