package ballistics.utils.math.minmax

class MinMaxCrushingCalculator : AbstractMinMaxCalculator() {
    override fun calculate(
        x1: Double,
        x2: Double,
        f: (Double) -> Double,
    ): Double? {
        var step = 1.0
        var iteration = 0
        var xk: Double = (x1 + x2) / 2
        var yk: Double
        var yk2: Double
        yk = f(xk)
        var xk2: Double = xk + step
        yk2 = f(xk2)
        var d = xk2 - xk
        if (d < 0) d *= -1.0

        while ((d >= delta) && (iteration < maxIterations)) {
            if (yk2 * sign > yk * sign) step = -step / 3
            xk = xk2
            yk = yk2
            xk2 = xk + step
            yk2 = f(xk2)
            d = xk2 - xk
            if (d < 0) d *= -1.0
            iteration++
        }

        return if (iteration < maxIterations) xk2 else null
    }
}
