我有一个问题,要计算模式(在数组中最频繁的数字)在斯威夫特。例如,在此代码中
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)
}
return nil
}
if let result = mostFrequent(array: [2,2,2,3,4,4,4,5,6]) {
print("\(result.value) is repeated \(result.count) times")
}打印:2被重复3次
我可以找到第一个最频繁的数字,也就是重复3次的2。但是你可以看到,如果有另外一个数字,也重复了3次,我不能通过使用这个函数看到它。例如,在我的数字数组中,2被重复3次,因此是模式。但有两种模式,即4种,也重复了3次。我想让这个函数显示这两种模式。有人能帮我指导我怎么做吗?
发布于 2018-01-15 00:33:27
您只需过滤与最大计数相等的结果,并映射它们的键:
func mostFrequent(array: [Int]) -> (mostFrequent: [Int], count: Int)? {
var counts: [Int: Int] = [:]
array.forEach { counts[$0] = (counts[$0] ?? 0) + 1 }
if let count = counts.max(by: {$0.value < $1.value})?.value {
return (counts.compactMap { $0.value == count ? $0.key : nil }, count)
}
return nil
}if let result = mostFrequent(array: [2, 2, 2, 3, 4, 4, 4, 5, 6]) {
print(result) // "(mostFrequent: [2, 4], count: 3)\n"
}编辑/更新:
extension Sequence where Element: Hashable {
var frequency: [Element: Int] { reduce(into: [:]) { $0[$1, default: 0] += 1 } }
var mostFrequent: (mostFrequent: [Element], count: Int)? {
guard let maxCount = frequency.values.max() else { return nil }
return (frequency.compactMap { $0.value == maxCount ? $0.key : nil }, maxCount)
}
}用法:
let array = [2,2,2,3,4,4,4,5,6]
if let mostFrequent = array.mostFrequent {
print("Most frequent", mostFrequent)
}这将打印:
最常见(mostFrequent: 2,4,计数: 3)
https://stackoverflow.com/questions/48255497
复制相似问题