我按照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*
但如果数组内的数字变异,结果会不断变化
,那就是使用noFrequentValuenoFrequentValue = [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
为什么当没有频繁值时,他们的代码会给出不同的结果?有多少?
没有频繁值时,这两种情况的默认值是什么?
答案 0 :(得分:2)
两种解决方案都包含无序结构中的计数。一种解决方案使用字典,另一种使用集合。字典或集合都不会保留值。尝试获取具有最高计数的值时,将返回随机值。
要修复它,您必须使用可以保持值排序的结构,例如一个数组。
合理的解决方案取决于要求。例如,您可以获取具有最高计数的所有值,并取其中最低值或最高值或原始数组中出现的第一个值。
答案 1 :(得分:2)
这是我原始答案的扩展版本。它提供了更多信息。
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.