Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

ios - Swift - Group elements of Array by value (2 by 2, 3 by 3, etc...)

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...