Last active
October 15, 2018 13:33
-
-
Save kristofk/58c0dd395578aab6150f325d2d9fadf8 to your computer and use it in GitHub Desktop.
Switch the rows and colums in Swift for vectors ( [[T]] ).
This file contains hidden or 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
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