EDIT: 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]
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
}
(With coef = 3, it would be: [2: 7, 5: 3, 8: 6]
-> 3 by 3)
I found nothing about that. Is it even possible ?
I am still a bit confused about the coefficient. However, let's suppose that what you want is to group any value
N
with the nextN+coefficient
values.Then I would start by remapping the original array into the group values:
Your question is so confusing that what
coef
means or can we expect the input array is sorted, what output type you want. There's noArray<Int, Int>
in Swift.Assuming the input array is sorted and you want
Array<(Int, Int)>
, you can write something like this:My code is not so efficient and there may be someone who can show you more efficient code.
It may have another simpler code as this:
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 orderAnd here is a recursive version of the above function