我从Swift 3: Getting the most frequent value of an array
我试过两个答案
@瓦卡瓦马
@幸福生活
如果数组具有频繁重复的值,则两个答案返回相同的结果:

var frequentValue = [1, 2, 2, 4]

//1. vacawama's code
var counts = [Int:Int]()
frequentValue.forEach{ counts[$0] = (counts[$0] ?? 0) + 1}
if let (value, count) = counts.maxElement({$0.1 < $1.1}){
    print("The result is: \(value)")
}
prints *The result is: 2*

//2. appzYourLife's code
let countedSet = NSCountedSet(array: frequentValue)
let most = countedSet.maxElement({countedSet.countForObject($0) < countedSet.countForObject($1)})
print("The result is: \(most!)")
*prints The result is: 2*

我注意到的是,如果没有频繁值,它们的代码将给出不同的结果。
var noFrequentValue = [1, 2, 3, 4]

//1. vacawama's code
prints *The result is: 2*

//2. appzYourLife's code
*prints The result is: 3*

但问题是如果数组中的数字发生变化,结果会不断变化,则使用nofrequentvalue
noFrequentValue = [1, 4]
//1. vacawama's code
prints The result is: 4

//2. appzYourLife's code
prints The result is: 1

noFrequentValue = [1, 2, 3, 5, 7]
//1. vacawama's code
prints The result is: 5

//2. appzYourLife's code
prints The result is: 7

noFrequentValue = [1, 2, 3, 0, etc...]

我尝试的另一件事是在数组中放入两个或多个具有相同频繁值的值
multipleFrequentValues = [1, 2, 2, 5, 7, 7, 9, 9]
//1. vacawama's code
prints The result is: 7

//2. appzYourLife's code
prints The result is: 7

multipleFrequentValues = [1, 2, 2, 5, 5, 7, 7, 9, 9 , 0, 0]
//1. vacawama's code
prints The result is: 5

//2. appzYourLife's code
prints The result is: 7

multipleFrequentValues = [2, 2, 8, 8]
//1. vacawama's code
prints The result is: 2

//2. appzYourLife's code
prints The result is: 8

为什么他们的代码在没有频繁值的情况下会给出不同的结果?
当没有频繁值时,对于这两种情况,什么是好的默认值?

最佳答案

这是我原来答案的扩展版。它提供了更多的信息。

var frequentValue = [1, 1, 2, 3, 3]

var counts = [Int : Int]()

frequentValue.forEach { counts[$0] = (counts[$0] ?? 0) + 1 }
if let (_, count) = counts.max(by: { $0.1 < $1.1 }) {
    if count == 1 {
        print("There are no repeated items.")
    } else {
        let all = counts.flatMap { $1 == count ? $0 : nil }
        if all.count == 1 {
            print("The most frequent item \(all.first!) is repeated \(count) times.")
        } else {
            print("The items \(all.sorted()) are repeated \(count) times each.")
        }
    }
} else {
    print("The array is empty.")
}

输出:
The items [1, 3] are repeated 2 times each.

关于arrays - 没有频繁值时如何处理数组中的频繁值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42846641/

10-15 13:25