0

This is my code:

val matrix1 = arrayOf(intArrayOf(1,2))
val matrix2 = arrayOf(intArrayOf(2), intArrayOf(1))
val product = Array(matrix1.size) { row ->
    IntArray(matrix2[0].size) { col ->
        matrix1[row].indices.reduce { acc, ind -> acc + (matrix1[row][ind] * matrix2[ind][col] }
    }
}

The answer to this matrix multiplication is 4. But the program returns 2. On analyzing different input matrices, I realized the first value is not added to acc.

This code should work like: 1*2 + 2*1 which would equal 4. But 1*2 part is either skipped or not added to acc.

How do I use reduce properly in this situation?

One Face
  • 417
  • 4
  • 10
  • 1
    The first time the lambda passed to `reduce` is executed, it will receive the first and second element of what you called it on as its parameters. You might want to use `fold` instead, which takes a separate starting value. See this answer for more: https://stackoverflow.com/a/44429568/4465208 – zsmb13 Apr 22 '20 at 07:36
  • Thank you that solved it. I feel dumb for not realizing it! – One Face Apr 22 '20 at 07:38
  • Please give it as the answer, I will accept it – One Face Apr 22 '20 at 07:38

0 Answers0