Multiplication of two-dimensional arrays in Scala

I can use the zip and map method to multiply a one-dimensional array.

I want to multiply two-dimensional arrays.

I have no idea. If i have two now

val x = Array(Array(1, 2),Array(3, 4),Array(5, 6))
val y = Array(Array(5, 10),Array(10, 15),Array(15, 20))

I want to get Array (Array (1 * 5, 2 * 10), Array (3 * 10, 4 * 15) ... etc.

In addition, I would like to get the sum of all internal arrays, for example: Array (1 * 5 + 2 * 10, 3 * 10 + 4 * 15 ....)

What is the perfect way to do this in Scala?

+4
source share
1 answer

Longer (more readable?) Version:

x.zip(y) map { case (xe, ye) =>
  xe.zip(ye).map { case (a, b) => a * b }
}

Oneliner:

x.zip(y) map (_.zipped map (_ * _))

Amount:

x.zip(y) map (_.zipped map (_ * _)) map (_.sum)
+3
source

All Articles