Skip to content

Instantly share code, notes, and snippets.

@pgebert
Last active December 13, 2023 18:22
Show Gist options
  • Save pgebert/02a49bc7a245ba2732df829beb64e73f to your computer and use it in GitHub Desktop.
Save pgebert/02a49bc7a245ba2732df829beb64e73f to your computer and use it in GitHub Desktop.
Transpose a list of lists in kotlin.
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