arrays - 如何在 swift 4 中计算数组的所有模式?

标签 arrays swift math

我现在使用的代码只提供一种模式,但如果有两种模式,则不会同时提供两种模式。

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

最佳答案

  1. 您的函数使用了一个从全局范围访问的数组变量。这是非常有限的,所以我将这些方法移到了 Array 的扩展中。这样,可以在具有任何兼容元素类型的任何数组上调用这些方法。
  2. 我将所有这些都变得通用。
  3. 我将函数的前 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/

相关文章:

python - 如何使用 unittest 正确编写测试?

python - 寻找 3D 曲面的开口

c++ - 计算3D中线和点之间的角度

arrays - 跳过和限制嵌套数组元素

c++ - 实现线程安全数组

c# - 通过结构指针将结构数组从 C# 传递到 C

java - 如何使用 Scala/Java 中的索引从另一个数组分配一个数组的元素?

swift - 如何解决 "Argument type ' CustomStruct'不符合预期类型 'Sequence'》

swift - Firebase 4.0 数据库引用错误

ios - 当您的应用程序快速运行时,检测 iOS 设备屏幕上显示的推送通知