获取数组

时间:2016-07-16 22:49:57

标签: arrays swift sorting

我有一个数字数组,我想知道这个数组中最常见的数字。数组有时有5-6个整数,有时它有10-12个,有时甚至更多 - 数组中的整数也可能不同。所以我需要一个可以使用不同长度和数组值的函数。

一个例子:

myArray = [0, 0, 0, 1, 1]

另一个例子:

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

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

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

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

8 个答案:

答案 0 :(得分:19)

您还可以使用NSCountedSet,这里是代码

let nums = [4, 4, 4, 3, 3, 3, 4, 6, 6, 5, 5, 2]
let countedSet = NSCountedSet(array: nums)
let mostFrequent = countedSet.max { countedSet.count(for: $0) < countedSet.count(for: $1) }

感谢@Ben Morrow在下面评论中提出的明智建议。

答案 1 :(得分:17)

let myArray = [4, 4, 4, 3, 3, 3, 4, 6, 6, 5, 5, 2]

// Create dictionary to map value to count   
var counts = [Int: Int]()

// Count the values with using forEach    
myArray.forEach { counts[$0] = (counts[$0] ?? 0) + 1 }

// Find the most frequent value and its count with max(by:)    
if let (value, count) = counts.max(by: {$0.1 < $1.1}) {
    print("\(value) occurs \(count) times")
}

输出:

4 occurs 4 times

这是一个功能:

func mostFrequent(array: [Int]) -> (value: Int, count: Int)? {
    var counts = [Int: Int]()

    array.forEach { counts[$0] = (counts[$0] ?? 0) + 1 }

    if let (value, count) = counts.max(by: {$0.1 < $1.1}) {
        return (value, count)
    }

    // array was empty
    return nil
}

if let result = mostFrequent(array: [1, 3, 2, 1, 1, 4, 5]) {
    print("\(result.value) occurs \(result.count) times")    
}
1 occurs 3 times

Swift 4的更新:

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

func mostFrequent<T: Hashable>(array: [T]) -> (value: T, count: Int)? {

    let counts = array.reduce(into: [:]) { $0[$1, default: 0] += 1 }

    if let (value, count) = counts.max(by: { $0.1 < $1.1 }) {
        return (value, count)
    }

    // array was empty
    return nil
}

if let result = mostFrequent(array: ["a", "b", "a", "c", "a", "b"]) {
    print("\(result.value) occurs \(result.count) times")
}
  
a occurs 3 times
  

答案 2 :(得分:7)

最常见的值称为“模式”。这是一个简洁的版本:

let mode = myArray.reduce([Int: Int]()) { 
    var counts = $0    
    counts[$1] = ($0[$1] ?? 0) + 1
    return counts 
}.max { $0.1 < $1.1 }?.0

这被认为是“不可读”还是“优雅”取决于你对更高阶功能的感受。尽管如此,这里它是Array扩展中的通用方法(因此它适用于任何Hashable元素类型):

extension Array where Element: Hashable {
    var mode: Element? {
        return self.reduce([Element: Int]()) { 
            var counts = $0
            counts[$1] = ($0[$1] ?? 0) + 1 
            return counts 
        }.max { $0.1 < $1.1 }?.0
    }
}

如果你想要一个包含模式计数的元组,只需删除.0

答案 3 :(得分:0)

func mostR(num:[Int]) - &gt; (编号:Int,totalRepeated:Int)

{     var numberTofind:Int = 0

var total : Int = 0

var dic : [Int : Int] = [:]

for index in num 
{
    if let count = dic[index]
    {
        dic[index] = count + 1 
    }
    else 
    {
        dic[index] = 1
    }

}

var high = dic.values.max()

for (index , count) in dic 
{
   if dic[index] == high 
   {  
       numberTofind = index
       top.append(count)
       total = count
   }

}
return (numberTofind , total)

}

var array = [1,22,33,55,4,3,2,0,0,0,0]

var result = mostR(num:[1,22,3,2,43,2,11,0,0,0])

print(“数字为(result.number),重复次数为:(result.totalRepeated)”)

答案 4 :(得分:0)

我尝试了以下代码。当最大计数适用于两个或多个值时,它特别有用。

var dictionary = arr.reduce(into: [:]) { counts, number in counts[number, default: 0] += 1}
var max = dictionary.values.max()!
dictionary = dictionary.filter{$0.1 == max}
mode = dictionary.keys.min()!

答案 5 :(得分:0)

这是一种封装/可重用的方法。

extension Array where Element: Hashable {
    
    /// The mode will be nil when the array is empty.
    var mode: Element? {
        var counts: [Element: Int] = [:]
        forEach { counts[$0] = (counts[$0] ?? 0) + 1 }
        if let (value, count) = counts.max(by: {$0.1 < $1.1}) {
            print("\(value) occurs \(count) times")
            return value
        } else {
            return nil
        }
    }
}

用法:

print([3, 4, 5, 6, 6].mode) // 6

答案 6 :(得分:0)

我对 Swift 5 的看法:

extension Collection {

    /**
     Returns the most frequent element in the collection.
     */
    func mostFrequent() -> Self.Element?
    where Self.Element: Hashable {
        let counts = self.reduce(into: [:]) {
            return $0[$1, default: 0] += 1
        }

        return counts.max(by: { $0.1 < $1.1 })?.key
    }
}

答案 7 :(得分:0)

跟踪每次出现,计算字典中每个键的值。这种情况仅适用于整数。将使用泛型更新此方法。

func mostCommon(of arr: [Int]) -> Int {
    var dict = [Int:Int]()
    arr.forEach {
        if let count = dict[$0] {
            dict[$0] = count + 1
        } else {
            dict[$0] = 1
        }
    }
    let max = dict.values.max()
    for (_ , value) in dict {
        if value == max {
            return value
        }
     }
    return -1
}