计算数组中特定整数的出现次数

时间:2015-12-14 02:06:16

标签: arrays swift

如何计算数组中特定数字出现的次数。 我无法为swift找到一种方法。有人可以指导我吗?

谢谢:)

2 个答案:

答案 0 :(得分:4)

Xcode 9或更高版本•Swift 4或更高版本

在Swift 4中,您可以使用新的Dictionary方法reduce(into:),如下所示:

extension Sequence where Element: Hashable {
    var frequency: [Element: Int] {
        return reduce(into: [:]) { $0[$1, default: 0] += 1 }
    }
    func frequency(of element: Element) -> Int {
        return frequency[element] ?? 0
    }
}

游乐场测试:

let numbers = [0, 0, 1, 1, 1, 2, 3, 4, 5, 5]
print(numbers.frequency) // [2: 1, 4: 1, 5: 2, 3: 1, 1: 3, 0: 2]

print(numbers.frequency(of: 0))   // 2  
print(numbers.frequency(of: 1))   // 3
print(numbers.frequency(of: 2))   // 1
print(numbers.frequency(of: 3))   // 1
print(numbers.frequency(of: 4))   // 1
print(numbers.frequency(of: 5))   // 2

通过扩展Collection,它也支持Strings

"aab".frequency   // ["a": 2, "b": 1]

答案 1 :(得分:3)

创建一个字典,在第一次找到它时存储该数字,并用1初始化该键。否则增加它。

let numArray = [1, 2, 2, 2, 5]
var numCount:[Int:Int] = [:]

for item in numArray {
    numCount[item] = (numCount[item] ?? 0) + 1

for (key, value) in numCount {
    println("\(key) occurs \(value) time(s)")
}