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
}
3
solved Swift – Group elements of Array by value (2 by 2, 3 by 3, etc…)