Search code examples
arraysscalaoperation

Scala: iteration 2d array to do operation


A newbie here.

val arr_one = Array(Array(1, 2), Array(3, 4), Array(5, 6),Array(x, y)..and so on)
val arr_two = Array(Array(2,3), Array(4, 5), Array(6, 7))
var tempArr = ArrayBuffer[Double]()

I want to multiply arr_one and arr_two. for example

Iteration1 :Array(1*2+2*3, 1*4 +2*5, 1*6+2*7 ) assign to tempArr

Iteration2 :Array(3*2+4*3, 3*4 +4*5, 3*6+4*7) assign to tempArr

Iteration3 :Array(5*2+6*3, 5*4 +6*5, 5*6+6*7) assign to tempArr

I knew that if

val x = Array(1, 2) ; val y = Array(Array(2,3), Array(4, 5), Array(6, 7))

I can use y map {x zip _ map{case(a, b) => a * b} sum}

But If x like arr_one form, I don't know how to use for loop or something else to do that.

I really have on idea.

How can I do this in scala?

Really thanks.


Solution

  • May be this is what you need:

    val tmp = arr_one map ((arr1) => {arr_two map (arr2 => (arr1 zip arr2) map {case(a, b) => a * b} reduce (_ + _))} )
    

    And to get ArrayBuffer simply use :

    tmpArr = tmp.toBuffer