swift-algorithms
swift-algorithms copied to clipboard
Consider add a transpose/rotate function for 2D arrays
Here's what I've cobbled together after Googling:
public extension Collection where Self.Iterator.Element : RandomAccessCollection {
func transpose() -> [[Self.Iterator.Element.Iterator.Element]] {
var transposed: [[Self.Iterator.Element.Iterator.Element]] = []
for column in 0..<(self.first?.count ?? 0) {
var temp: [Self.Iterator.Element.Iterator.Element] = []
for row in 0...self.count - 1 {
temp.append(self[row as! Self.Index][column as! Self.Element.Index])
}
transposed.append(temp)
}
return transposed
}
}
As always, I'm hoping the pros can create something more general and performant.