Search
 
SCRIPT & CODE EXAMPLE
 

SWIFT

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")    
}
Comment

PREVIOUS NEXT
Code Example
Swift :: swift add programmatically constraint to view 
Swift :: string value of enum swift 
Swift :: hex color swiftui 
Swift :: Swift Swift continue statement with nested loops 
Swift :: hide scroll view indicators bar swiftui 
Swift :: swiftui actionsheet 
Swift :: how to covert a string into a float in swift 
Swift :: swift screenshot 
Swift :: uilabel make bold 
Swift :: swift convert string to int 
Swift :: if else if and else statments in swift language 
Swift :: find range of string swift 
Swift :: swiftui textfield focus 
Swift :: swift array index of where 
Swift :: swift check if regex is in string 
Swift :: uilabel center text programmatically swift 
Swift :: swift create lazy property 
Swift :: Swift Named Tuples 
Swift :: how to add dragdown gesture recognizer on view 
Swift :: xcode how to get aspect ratio of device 
Swift :: rotate sfsymbol horizontal flip swiftui 
Swift :: how to darken view swiftui 
Swift :: Swift Create enum variables 
Swift :: how to call another view controller method when button click from another ios swift 
Swift :: how to change the tint color of tab bar on storyboard swift 
Swift :: Function Call Using try Keyword Swift 
Swift :: Arithmetic Operators in Swift 
Swift :: spilit string in swift 
Swift :: xcode combine calayer into an image 
Ruby :: activerecord list tables 
ADD CONTENT
Topic
Content
Source link
Name
4+4 =