apple / swift-algorithms

Commonly used sequence and collection algorithms for Swift
Apache License 2.0
5.9k stars 435 forks source link

Consider add a transpose/rotate function for 2D arrays #214

Closed fwgreen closed 5 months ago

fwgreen commented 9 months ago

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.