Skip to content

Instantly share code, notes, and snippets.

@Turskyi
Created April 20, 2022 21:29
Show Gist options
  • Save Turskyi/4893dece0ebc96912ddd6666bec0f078 to your computer and use it in GitHub Desktop.
Save Turskyi/4893dece0ebc96912ddd6666bec0f078 to your computer and use it in GitHub Desktop.
Given a 2D integer array matrix, return the transpose of matrix. The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
/*
Given a 2D matrix, return the matrix transposed.
Note: The transpose of a matrix is an operation that flips each value in the matrix across its main diagonal.
Ex: Given the following matrix…
matrix = [
[1, 2],
[3, 4]
]
return a matrix that looks as follows...
[
[1,3],
[2,4]
]
* */
fun transpose(matrix: Array<IntArray>): Array<IntArray> {
val rowSize: Int = matrix.size
val colSize: Int = matrix[0].size
val transposed: Array<IntArray> = Array(colSize) { IntArray(rowSize) }
for (i: Int in 0 until rowSize * colSize) {
val x: Int = i / colSize
val y: Int = i % colSize
transposed[y][x] = matrix[x][y]
}
return transposed
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment