Last active
December 13, 2023 18:22
-
-
Save pgebert/02a49bc7a245ba2732df829beb64e73f to your computer and use it in GitHub Desktop.
Transpose a list of lists in kotlin.
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
fun <T> List<List<T>>.transpose(): List<List<T>> { | |
var transposed = mutableListOf<List<T>>() | |
for (i in first().indices) { | |
val col: MutableList<T> = ArrayList() | |
forEach { row -> | |
col.add(row[i]) | |
} | |
transposed.add(col) | |
} | |
return transposed | |
} | |
// Example: | |
listOf(listOf('a', 'b'), listOf('a', 'b')).transpose() // -> listOf(listOf('a', 'a'), listOf('b', 'b')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment