当没有频繁值时如何处理数组中的频繁值

What to do for a frequent value in array when there are no frequent values

我遵循了

的答案

我尝试了 2 个答案

  1. @vacawama
  2. @appzYourLife

他们的两个答案 return 如果数组具有频繁重复出现的值,则结果相同:

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

//1. vacawama's code
var counts = [Int:Int]()
frequentValue.forEach{ counts[[=10=]] = (counts[[=10=]] ?? 0) + 1}
if let (value, count) = counts.maxElement({[=10=].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([=10=]) < countedSet.countForObject()})
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...]

我尝试的另一件事是将 2 个或更多具有相同频繁值的值放入数组中

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[[=10=]] = (counts[[=10=]] ?? 0) + 1 }
if let (_, count) = counts.max(by: { [=10=].1 < .1 }) {
    if count == 1 {
        print("There are no repeated items.")
    } else {
        let all = counts.flatMap {  == count ? [=10=] : 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.