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
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)