Answers for "most frequent element in array swift"

0

most frequent element in array swift

func mostFrequent(array: [Int]) -> (value: Int, count: Int)? {
    var counts = [Int: Int]()

    array.forEach { counts[$0] = (counts[$0] ?? 0) + 1 }

    if let (value, count) = counts.max(by: {$0.1 < $1.1}) {
        return (value, count)
    }

    // array was empty
    return nil
}

if let result = mostFrequent(array: [1, 3, 2, 1, 1, 4, 5]) {
    print("(result.value) occurs (result.count) times")    
}
Posted by: Guest on December-21-2021

Code answers related to "most frequent element in array swift"

Code answers related to "Swift"

Browse Popular Code Answers by Language