Skip to content

Instantly share code, notes, and snippets.

@kristofk
Last active October 15, 2018 13:33
Show Gist options
  • Save kristofk/58c0dd395578aab6150f325d2d9fadf8 to your computer and use it in GitHub Desktop.
Save kristofk/58c0dd395578aab6150f325d2d9fadf8 to your computer and use it in GitHub Desktop.
Switch the rows and colums in Swift for vectors ( [[T]] ).
func determineLongestItem<T>(in matrix: [[T]]) -> Int {
var maxLength = 0
for item in matrix {
if item.count > maxLength {
maxLength = item.count
}
}
return maxLength
}
func switchMatrixVectors<T>(for originalMatrix: [[T]]) -> [[T?]] {
let longestItemInOriginalMatrix = determineLongestItem(in: originalMatrix)
//Create an empty matrix of the same size
var newMatrix = [[T?]]()
for _ in 1...longestItemInOriginalMatrix {
newMatrix.append([])
}
// Fill up data
for index in 0...determineLongestItem(in: originalMatrix) - 1 {
for row in originalMatrix {
if index < row.count {
newMatrix[index].append(row[index])
} else {
newMatrix[index].append(nil)
}
}
}
return newMatrix
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment