Problem
Given an array of values , how can I split it into sub-arrays from elements that are equal?
Example
Given this array
let numbers = [1, 1, 1, 3, 3, 4]
I want this conclusion
[[1,1,1], [3, 3], [4]]
What I am NOT looking for
A possible way to resolve this issue is to create some kind of index to indicate the occurrences of each element like this.
let indexes = [1:3, 3:2, 4:1]
And finally, use the index to rebuild the output array.
let subsequences = indexes.sort { $0.0.0 < $0.1.0 }.reduce([Int]()) { (res, elm) -> [Int] in return res + [Int](count: elm.1, repeatedValue: elm.0) }
However, with this solution, I lose my original values. Of course, in this case it is not a big problem (the value of Int is still and Int even if recreated), but I would like to apply this solution to more complex data structures, such as
struct Starship: Equatable { let name: String let warpSpeed: Int } func ==(left:Starship, right:Starship) -> Bool { return left.warpSpeed == right.warpSpeed }
Final considerations
The function I'm looking for will be something like the inverse of flatten() , infact
let subsequences: [[Int]] = [[1,1,1], [3, 3], [4]] print(Array(subsequences.flatten())) // [1, 1, 1, 3, 3, 4]
I hope I made it clear, let me know if you need more information.