I want tot transpose a matrix. I was so impressed by swap function in kotlin.
var a = 1
var b = 2
a = b.also { b = a }
println(a) // print 2
println(b) // print 1
Now I'm trying to use it on my transpose function (I found it only works on sqaure matrix but that's not the point).
class Matrix(val matrix : Array<DoubleArray>){
val rowSize = matrix.size
val colSize = matrix[0].size
}
fun transposeMatrix(matrix: Matrix): Matrix {
return Matrix(matrix.matrix.mapIndexed { rowindex, row ->
row.mapIndexed { colindex, element ->
if (rowindex > colindex) {
matrix.matrix[colindex][rowindex].also {
matrix.matrix[colindex][rowindex] = element
} // this one should "swap" two elements
} else {
element
}
}.toDoubleArray()
}.toTypedArray())
}
"swap" part doesn't work.
Enter new matrix: 3 6 9 2 5 10 1 1 0.5 3.0 6.0 9.0 6.0 5.0 10.0 9.0 10.0 0.5
I think that part is equal to
element = matrix.matrix[colindex][rowindex].also {matrix.matrix[colindex][rowindex] = element}
which perfectly matches format.
Now i'm really confused. What's the difference between two codes? why my one is not working?