LoginSignup
2
1

More than 3 years have passed since last update.

Kotlinで二次元リストの行と列を入れ替える

Last updated at Posted at 2020-06-22

Kotlin で二次元リストの行と列を入れ替える関数が欲しくなったとき、
大変参考になる JavaScript の記事 を発見しましたので、Kotlin版を作ってみました。

関数

function
fun <T> transpose(list: List<List<T>>): List<List<T>> =
    list.first().mapIndexed { index, _ ->
        list.map { row -> row[index] }
    }

使用例

sample
fun main(args: Array<String>) {
    val list1: List<List<Char>> = listOf(
        listOf('a', 'b', 'c'),
        listOf('d', 'e', 'f'),
        listOf('g', 'h', 'i')
    )

    println(list1)
    // => [[a, b, c], [d, e, f], [g, h, i]]

    println(transpose(list1))
    // => [[a, d, g], [b, e, h], [c, f, i]]

    val list2: List<List<Int>> = listOf(
        listOf(1, 2, 3),
        listOf(4, 5, 6),
        listOf(7, 8, 9)
    )

    println(list2)
    // => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

    println(transpose(list2))
    // => [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
}
2
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1