数组 – 获取数组的最常见值

前端之家收集整理的这篇文章主要介绍了数组 – 获取数组的最常见值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个数字数组,我想知道这个数组中最常见的数字.数组有时有5-6个整数,有时它有10-12个,有时甚至更多 – 数组中的整数也可能不同.所以我需要一个可以使用不同长度和数组值的函数.

一个例子:

  1. myArray = [0,1,1]

另一个例子:

  1. myArray = [4,4,3,6,5,2]

现在我正在寻找一个函数,它给出0(在第一个例子中)为Integer,因为它在这个数组中是3次,而数组中的另一个整数(1)在数组中只有2次.或者对于第二个例子,它将是4.

看起来很简单,但我找不到解决方案.在网络上找到了一些例子,其解决方案是使用字典或解决方案很简单 – 但我似乎无法使用它与Swift 3 …

但是,我没有找到适合我的解决方案.有人知道如何在整数数组中获得最频繁的整数?

  1. let myArray = [4,2]
  2.  
  3. // Create dictionary to map value to count
  4. var counts = [Int: Int]()
  5.  
  6. // Count the values with using forEach
  7. myArray.forEach { counts[$0] = (counts[$0] ?? 0) + 1 }
  8.  
  9. // Find the most frequent value and its count with max(by:)
  10. if let (value,count) = counts.max(by: {$0.1 < $1.1}) {
  11. print("\(value) occurs \(count) times")
  12. }

输出

06001

这是一个功能

  1. func mostFrequent(array: [Int]) -> (value: Int,count: Int)? {
  2. var counts = [Int: Int]()
  3.  
  4. array.forEach { counts[$0] = (counts[$0] ?? 0) + 1 }
  5.  
  6. if let (value,count) = counts.max(by: {$0.1 < $1.1}) {
  7. return (value,count)
  8. }
  9.  
  10. // array was empty
  11. return nil
  12. }
  13.  
  14. if let result = mostFrequent(array: [1,2,5]) {
  15. print("\(result.value) occurs \(result.count) times")
  16. }

06003

Swift 4的更新:

Swift 4引入了reduce(into:_ :)和数组查找的默认值,使您能够在一个有效的行中生成频率.我们也可以将它设为通用的,并使其适用于Hashable的任何类型:

  1. func mostFrequent<T: Hashable>(array: [T]) -> (value: T,count: Int)? {
  2.  
  3. let counts = array.reduce(into: [:]) { $0[$1,default: 0] += 1 }
  4.  
  5. if let (value,count) = counts.max(by: { $0.1 < $1.1 }) {
  6. return (value,count)
  7. }
  8.  
  9. // array was empty
  10. return nil
  11. }
  12.  
  13. if let result = mostFrequent(array: ["a","b","a","c","b"]) {
  14. print("\(result.value) occurs \(result.count) times")
  15. }

06005

猜你在找的Swift相关文章