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?