What is the easiest way to transpose 2 dimentional...
# announcements
i
What is the easiest way to transpose 2 dimentional list in kotlin?
Copy code
// now
listOf(
            listOf(1, 2),
            listOf(3, 4)
        )

// want
listOf(
            listOf(3, 1),
            listOf(4, 2)
        )
r
My proposition 🙂
Copy code
with(now.reversed()) {
    (0..1).map { i -> map { it[i] } }
}
Of course it works only for 2x2 😉
h
typealias Vector = DoubleArray typealias Matrix = Array<Vector> fun Matrix.transpose(): Matrix { val rows = this.size val cols = this[0].size val trans = Matrix(cols) { Vector(rows) } for (i in 0 until cols) { for (j in 0 until rows) trans[i][j] = this[j][i] } return trans }
388 Views