Skip to content

Instantly share code, notes, and snippets.

@t0rn
Created October 14, 2020 10:15
Show Gist options
  • Save t0rn/5f5e0ec25ab12a5f3db4335f1eb2095f to your computer and use it in GitHub Desktop.
Save t0rn/5f5e0ec25ab12a5f3db4335f1eb2095f to your computer and use it in GitHub Desktop.
extension Collection where Element: Collection {
func transposed() -> [[Element.Element]]? {
guard let maxCount = self.map({$0.count}).max() else {return nil}
var result = [[Element.Element?]](repeating: [Element.Element?](repeating: nil, count: self.count), count: maxCount)
for (r,row) in self.enumerated() {
for (c,v) in row.enumerated() {
result[c][r] = v
}
}
return result
.map { (elements) -> [Element.Element] in
elements.compactMap{$0}
}
}
}
let test1 = [
[],
[1,2,3],
[4,5]
]
let test2 = [
[1,2],
[3,4,5,6,7],
[],
[8],
[]
]
test1.transposed() == [[1,4], [2,5], [3]]
test2.transposed() == [[1,3,8], [2,4], [5], [6], [7]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment