0

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?

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
jisoo
  • 35
  • 4

1 Answers1

0

I found the answer.
Forget about matrix. The problem here is "map"function does not change collection itself,but it creates new one.

Enter new matrix:
3 6 9
2 5 10
1 1 0.5

mapping first row works perfectly
first:
3 6 9
2 5 10
1 1 0.5
mapped:
3 6 9
problem starts with (2,1)(index 1,0)

by if (rowindex > colindex) { matrix.matrix[colindex][rowindex]

mapped:
    3 6 9
    6
and then by "also" func  matrix.matrix[colindex][rowindex] = element 
first:
    3 6 9
    2->2 5 10
    1 1 0.5

and here "Swap" fails.

jisoo
  • 35
  • 4