Requirements are as follows:
1. An array is known, and the number of single elements in the array is used as the basis for reordering.
2. When the number is the same, the row with the largest element value is in front
example:
[1, 2, 2, 3, 5, 5]
The calculated result is:
[5, 5, 2, 2, 3, 1]
One solution is:
import UIKit
extension Sequence where Iterator.Element == Int {
private func removeRepeats ()-> [Int] {
let set = Set (self)
return Array (set) .sorted {$ 0> $ 1}
}
private func countFor (value: Int)-> Int {
return filter {$ 0 == value} .count
}
func sortByRepeatCount ()-> [Iterator.Element] {
var wets = [[Int]] ()
let clearedAry = removeRepeats ()
for i in clearedAry {
wets.append ([i, countFor (value: i)])
}
wets = wets.sorted {
$ 0 [1]> $ 1 [1]
}
var result = [Int] ()
for x in wets {
let i = x [0]
let count = x [1]
for _ in 0 .. <count {
result.append (i)
}
}
return result
}
}
var ary = [1,1,2,1,3,3,4,5,4,6,6,6]
print (ary.sortByRepeatCount ())
// Output "[6, 6, 6, 1, 1, 1, 4, 4, 3, 3, 5, 2] \ n"
Other netizens provide a more intuitive and simple method:
extension SequenceType where Generator.Element: Hashable {
func frequencies ()-> [Generator.Element: Int] {
var results: [Generator.Element: Int] = [:]
for element in self {
results [element] = (results [element] ?? 0) + 1
}
return results
}
}
let alpha = [2,8,2,6,1,8,2,6,6]
let beta = [6,6,6,2,2,2,8,8,1]
let sorted = alpha.frequencies (). sort {
if $ 0.1> $ 1.1 {// if the frequency is higher, return true
return true
} else if $ 0.1 == $ 1.1 {// if the frequency is equal
return $ 0.0> $ 1.0 // return value is higher
} else {
return false // else return false
}
}
Note that the latter solution can only be run in Swift 2.x, if you want to run in Swift 3, you need to modify it slightly, please refer to another blog post I wrote:
How to write a limited type extension for Array in Swift3
Swift sorts according to the number and size of array elements