How to transpose a matrix (swap rows and columns) in Kotlin

4 Answers

0 votes
// using map
fun transpose(matrix: List<List<Int>>): List<List<Int>> =
    matrix[0].indices.map { col ->
        matrix.map { row -> row[col] }
    }

fun main() {
    val matrix = listOf(
        listOf(1, 2, 3),
        listOf(4, 5, 6),
        listOf(7, 8, 9)
    )

    val t = transpose(matrix)
    t.forEach { println(it.joinToString(" ")) }
}


/*
run:

1 4 7
2 5 8
3 6 9

*/

 



answered 21 hours ago by avibootz
0 votes
// using loop
fun transpose(matrix: List<List<Int>>): List<List<Int>> {
    val rows = matrix.size
    val cols = matrix[0].size

    val result = MutableList(cols) { MutableList(rows) { 0 } }

    for (i in 0 until rows) {
        for (j in 0 until cols) {
            result[j][i] = matrix[i][j]
        }
    }

    return result
}

fun main() {
    val matrix = listOf(
        listOf(1, 2, 3),
        listOf(4, 5, 6),
        listOf(7, 8, 9)
    )

    val t = transpose(matrix)
    t.forEach { println(it.joinToString(" ")) }
}



/*
run:

1 4 7
2 5 8
3 6 9

*/

 



answered 21 hours ago by avibootz
0 votes
// using extension function
fun <T> List<List<T>>.transpose(): List<List<T>> =
    this[0].indices.map { col ->
        this.map { row -> row[col] }
    }

fun main() {
    val matrix = listOf(
        listOf(1, 2, 3),
        listOf(4, 5, 6),
        listOf(7, 8, 9)
    )

    val t = matrix.transpose()
    t.forEach { println(it.joinToString(" ")) }
}



/*
run:

1 4 7
2 5 8
3 6 9

*/

 



answered 21 hours ago by avibootz
0 votes
// using array
fun transpose(matrix: Array<IntArray>): Array<IntArray> {
    val rows = matrix.size
    val cols = matrix[0].size

    val result = Array(cols) { IntArray(rows) }

    for (i in 0 until rows) {
        for (j in 0 until cols) {
            result[j][i] = matrix[i][j]
        }
    }

    return result
}

fun main() {
    val matrix = arrayOf(
        intArrayOf(1, 2, 3),
        intArrayOf(4, 5, 6),
        intArrayOf(7, 8, 9)
    )

    val t = transpose(matrix)
    t.forEach { println(it.joinToString(" ")) }
}



/*
run:

1 4 7
2 5 8
3 6 9

*/

 



answered 21 hours ago by avibootz
...