/*
 * Copyright 2024 <NAME>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package dev.shtanko.algorithms.leetcode

import dev.shtanko.algorithms.math.gcd
import kotlin.math.max
import kotlin.math.min

/**
 * 1979. Find Greatest Common Divisor of Array
 * @see <a href="https://leetcode.com/problems/find-greatest-common-divisor-of-array">Source</a>
 */
fun interface GreatestCommonDivisorOfArray {
    operator fun invoke(nums: IntArray): Int
}

class GreatestCommonDivisorOfArrayBF : GreatestCommonDivisorOfArray {
    override fun invoke(nums: IntArray): Int {
        if (nums.isEmpty()) return -1
        nums.sort()
        val smallest = nums.first()
        val largest = nums.last()
        return gcd(smallest, largest)
    }
}

class Euclidean : GreatestCommonDivisorOfArray {
    override fun invoke(nums: IntArray): Int {
        var min = Int.MAX_VALUE
        var max = Int.MIN_VALUE
        for (num in nums) {
            min = if (min > num) num else min
            max = if (max < num) num else max
        }
        return gcd(min, max)
    }
}

class GreatestCommonDivisorOfArrayFunc : GreatestCommonDivisorOfArray {
    override fun invoke(nums: IntArray): Int {
        return nums
            .fold(Pair(Int.MIN_VALUE, Int.MAX_VALUE)) { prev, curr ->
                Pair(
                    max(prev.first, curr),
                    min(prev.second, curr),
                )
            }
            .let { gcd(it.first, it.second) }
    }
}
