Most common array elements

前端 未结 3 1199
南笙
南笙 2020-12-11 08:36

I need to find the most common (modal) elements in an array.

The simplest way I could think of was to set variables for each unique element, and assign a count vari

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-11 09:06

    For XCode 7.1 the solution is.

    // Array of elements
    let a = [7,3,2,1,4,6,8,9,5,3,0,7,2,7]
    
    // Create a key for elements and their frequency
    var times: [Int: Int] = [:]
    
    // Iterate over the dictionary
    for b in a {
        // Every time there is a repeat value add one to that key
        times[b] = (times[b] ?? 0) + 1
    }
    
    // This is for sorting the values
    let decending = times.sort({$0.1 > $1.1})
    // For sorting the keys the code would be 
    // let decending = times.sort({$0.0 > $1.0})
    // Do whatever you want with sorted array
    print(decending)
    

提交回复
热议问题