我有一个数字数组,我想知道该数组中哪个数字最常见。数组有时包含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中使用它...
但是,我没有找到适合我的解决方案。有人知道如何获取整数数组中最频繁的整数?
最佳答案
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")
}
输出:
这是一个函数:
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")
}
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")
}
关于arrays - 获取数组的最频繁值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38416347/