'Multidimensional Array zip array in scala
I have two array like:
val one = Array(1, 2, 3, 4)
val two = Array(4, 5, 6, 7)
var three = one zip two map{case(a, b) => a * b}
It's ok.
But I have a multidimensional Array and a one-dimensional array now, like this:
val mulOne = Array(Array(1, 2, 3, 4),Array(5, 6, 7, 8),Array(9, 10, 11, 12))
val one_arr = Array(1, 2, 3, 4)
I would like to multiplication them, how can I do this in scala?
Solution 1:[1]
You could use:
val tmpArr = mulOne.map(_ zip one_arr).map(_.map{case(a,b) => a*b})
This would give you Array(Array(1*1, 2*2, 3*3, 4*4), Array(5*1, 6*2, 7*3, 8*4), Array(9*1, 10*2, 11*3, 12*4))
.
Here mulOne.map(_ zip one_arr)
maps each internal array of mulOne
with corresponding element of one_arr
to create pairs like: Array(Array((1,1), (2,2), (3,3), (4,4)), ..)
(Note: I have used placeholder syntax). In the next step .map(_.map{case(a,b) => a*b})
multiplies each elements of pair to give
output like: Array(Array(1, 4, 9, 16),..)
Then you could use:
tmpArr.map(_.reduce(_ + _))
to get sum of all internal Array
s to get Array(30, 70, 110)
Solution 2:[2]
Try this
mulOne.map{x => (x, one_arr)}.map { case(one, two) => one zip two map{case(a, b) => a * b} }
mulOne.map{x => (x, one_arr)}
=> for every array inside mulOne
, create a tuple with content of one_arr.
.map { case(one, two) => one zip two map{case(a, b) => a * b} }
is basically the operation that you performed in your first example on every tuple that were created in the first step.
Solution 3:[3]
Using a for comprehension like this,
val prods =
for { xs <- mulOne
zx = one_arr zip xs
(a,b) <- zx
} yield a*b
and so
prods.sum
delivers the final result.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | mohit |
Solution 3 | elm |