我现在使用的代码只提供一种模式,但如果有两种模式,则不会同时提供两种模式。
func Mode() -> Float {
var occurances: [Int: Int] = [:]
for number in array {
if var value = occurances[number] {
occurances[number] = value + 1
} else {
occurances[number] = 1
}
}
var highestKeyPair: (key: Int, value: Int) = (0,0)
for (key,value) in occurances {
highestKeyPair = (value > highestKeyPair.value) ? (key,value): highestKeyPair
}
let mode = highestKeyPair.key
return Float(mode)
}
最佳答案
- 您的函数使用了一个从全局范围访问的
数组
变量。这是非常有限的,所以我将这些方法移到了 Array 的扩展中。这样,可以在具有任何兼容元素类型的任何数组上调用这些方法。 - 我将所有这些都变得通用。
- 我将函数的前 8 行提取到其自己的
countOccurrences()
方法中。我使用Array.reduce(into:)
重新实现了它和Dictionary.subscript(_:default)
这是我的实现方法:
extension Array where Element: Hashable {
func countOccurrences() -> [Element: Int] {
return self.reduce(into: [:]) { (occurences, element) in occurences[element, default: 0] += 1}
}
func mode() -> [Element] {
// Keeps track of the fist mode's num occurences.
// Every other element with the same number of occurences is also a mode.
var firstModeNumOccurences: Int? = nil
let modes = countOccurrences()
.sorted { pairA, pairB in pairA.value > pairB.value } // sorting in descending order of num occurences
.lazy
.prefix(while:) { (element, numOccurences) in // Take all elements with the same num occurences
if firstModeNumOccurences == nil { firstModeNumOccurences = numOccurences }
return numOccurences == firstModeNumOccurences
}
.map { (element, _) in element } // keep only the elements, not their counts
return Array(modes)
}
}
关于arrays - 如何在 swift 4 中计算数组的所有模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50633832/