Swift-按值对Array的元素进行分组(2 x 2、3 x 3等) [英] Swift - Group elements of Array by value (2 by 2, 3 by 3, etc...)
问题描述
编辑:我不是在要求函数对事件进行计数。我要一个函数来统计发生次数 2乘2 , 3乘3 , 10乘10 等,这是我的问题
I'm not asking a function to count an occurence. I'm asking a function to count an occurence 2 by 2, 3 by 3, 10 by 10, etc... this is my problem
我有一系列分数,可以说:
I have an array of scores, lets say:
[2,2,3,4,4,4,4,5,6,6,8,8,8,9,10,10]
我希望有一个函数可以将此 Array
转换为 Dictionary [Int:Int] ()
具有类似的内容:
I would like to have a function that transform this Array
into a Dictionary [Int: Int]()
to have something like that:
func groupArrayBy(array: Array<Int>, coef: Int) -> Array<Int, Int>{
// if coef = 2 -> 2 by 2, count occurence
// Transform the array to:
// [2: 3, 4: 5, 6: 2, 8: 4, 10: 2]
// return Dictionary
}
(当coef = 3时,将是: [2:7,5:3,8:6]
-> 3 3)
(With coef = 3, it would be: [2: 7, 5: 3, 8: 6]
-> 3 by 3)
我对此一无所获。可能吗?
I found nothing about that. Is it even possible ?
推荐答案
这是我的版本,其中我根据数组的第一个值和过滤范围coef
变量,根据结果,我将那些已经计数的元素切掉,并在循环中再次过滤较小的数组。此解决方案要求输入数组以升序排序
Here is my version where I filter on a range based on first value of the array and the coef
variable, based on the result I slice away those elements already counted and filter again on the smaller array in a loop. This solution requires the input array to be sorted in ascending order
func group(_ array: [Int], coef: Int) -> [Int: Int] {
var result:[Int:Int] = [:]
var start = array[0]
var end = start + coef - 1
var arr = array
while start <= array[array.count - 1] {
let count = arr.filter({ $0 >= start && $0 <= end}).count
result[start] = count
start = end + 1
end = start + coef - 1
arr = Array(arr[count...])
}
return result
}
这是上述函数的递归版本
And here is a recursive version of the above function
func group(_ array: [Int], coef: Int) -> [Int: Int] {
var result:[Int:Int] = [:]
if array.isEmpty { return result }
let end = array[0] + coef - 1
let count = array.filter({ $0 >= array[0] && $0 <= end}).count
result[array[0]] = count
result = result.merging(group(Array(array[count...]), coef: coef)) { $1 }
return result
}
这篇关于Swift-按值对Array的元素进行分组(2 x 2、3 x 3等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!