Created
November 8, 2022 17:27
-
-
Save gchumillas/66ac0417b320f9799ce7d9e82b499447 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Array where Element: Collection { | |
// Calculates the size of a matrix. | |
func size() -> (cols: Int, rows: Int) { | |
let numRows = self.count | |
let numCols = self.reduce(0, { Swift.max($0, $1.count) }) | |
return (numCols, numRows) | |
} | |
// Transposes a matrix. | |
// | |
// For example: | |
// | |
// let m = [[1, 2], [4, 5, 6]] | |
// print(m.transposed(with: -1)) // outputs: [[1, 4], [2, 5], [-1, 6]] | |
// | |
// let m = [["a", "b", "c"], ["d", "e"]] | |
// print(m.transposed(with: " ")) // outputs: [["a", "d"], ["b", "e"], ["c", " "]] | |
func transposed(with char: Element.Element) -> [[Element.Element]] { | |
let (numCols, numRows) = self.size() | |
var result = (0..<numCols).map { _ in (0..<numRows).map {_ in char } } | |
for (i, row) in self.enumerated() { | |
for (j, cell) in row.enumerated() { | |
result[j][i] = cell | |
} | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment