算上一个特定的整数在数组中的OCCURENCES [英] Count the occurences a particular integer has in an array

查看:145
本文介绍了算上一个特定的整数在数组中的OCCURENCES的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算在阵列中出现的特定数目的次数。
我不能找到这个为迅速的方法。有人可以指导我吗?

How to count the number of times a particular number occurs in an array. I cant find a method for this for swift. can someone guide me please?

感谢:)

推荐答案

尝试这样的:

let numbers = [1,2,3,4,3,4]


//create a dictionary to store the integers ocurrencies: 
var occurrences: [Int:Int] = [:]

// iterate through the numbers in your array using a loop
for number in numbers {
    // add a new key or increase it
    occurrences[number] = (occurrences[number] ?? 0) + 1
}

// you can also use forEach
numbers.forEach{occurrences[$0] = (occurrences[$0] ?? 0).successor()}

print(occurrences)   // [2: 1, 3: 2, 1: 1, 4: 2]

您也可以创建一个扩展数组,其中的元素是可哈希:

You can also create an extension array where Elements are hashable:

extension Array where Element: Hashable {
    var occurrences: [Element:Int] {
        var result: [Element:Int] = [:]
        forEach{ result[$0] = (result[$0] ?? 0).successor() }
        return result
    }
    func occurrencesOf(element element: Element) -> Int {
        return occurrences[element] ?? 0
    }
}

测试

print(numbers.occurrences) // [2: 1, 3: 2, 1: 1, 4: 2]

print(numbers.occurrencesOf(element: 0))   // 0
print(numbers.occurrencesOf(element: 1))   // 1
print(numbers.occurrencesOf(element: 2))   // 1
print(numbers.occurrencesOf(element: 3))   // 2
print(numbers.occurrencesOf(element: 4))   // 2
print(numbers.occurrencesOf(element: 5))   // 0

这篇关于算上一个特定的整数在数组中的OCCURENCES的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆