Arrays 如何计算swift 4中阵列的所有模式?
我现在使用的代码只提供一种模式,但如果有两种模式,则不会同时提供两种模式Arrays 如何计算swift 4中阵列的所有模式?,arrays,swift,math,Arrays,Swift,Math,我现在使用的代码只提供一种模式,但如果有两种模式,则不会同时提供两种模式 func Mode() -> Float { var occurances: [Int: Int] = [:] for number in array { if var value = occurances[number] { occurances[number] = value + 1 } else {
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)
}
数组
变量。这是非常有限的,所以我将这些方法移到了数组的扩展中。通过这种方式,这些方法可以在具有任何兼容元素类型的任何数组上调用李>
countoccurrencess()
方法中。我使用和重新实现了它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)
}
}
首先,我建议你把它分解一下。将计算发生次数的第一部分提取到函数中。也许
计数发生次数
。然后再考虑如何在其中找到前2个值。做得很好,但我怀疑泛型会让OP和大多数开始中级Swift开发人员迷失方向。(除了那些熟悉其他语言概念的人)是的,但对于扩展、闭包、函数式编程风格也是如此,这就是为什么我在评论中对出现的问题做出回应。我建议首先给出一个狭隘的答案,用最少的高级主题(如泛型)来解决这个问题,然后是“现在,如果我们使用泛型,我们可以使函数对更广泛的数组类型更有用”所以你向OP和其他读者展示了这个概念。