2

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?

2
  • What do you want your output to be? Commented Apr 22, 2016 at 9:57
  • 1*1 + 2*2 + 3*3 +4*4 5*1 + 6*2 + 7*3 + 8*4 ..... Commented Apr 22, 2016 at 9:59

3 Answers 3

2

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 Arrays to get Array(30, 70, 110)

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

It's helpful for me, too. Thanks
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.