1

I have 2 d array:

val arr =Array(Array(2,1),Array(3,1),Array(4,1))

I should multiply all inner 1st elements and sum all inner 2nd elements to get as result:

Array(24,3)

I`m looking a way to use map there, something like :

arr.map(a=>Array(a(1stElemnt).product , a(2ndElemnt).sum )) 

Any suggestion Regards.

2
  • 1
    If you are sure that your nested Arrays will always have two elements it would be better to have an array of Tuples. Even better, use a List, Vector, ArrayaSeq or any other real collection, instead of plain arrays. - Anyways, you can solve this using foldLeft instead. Commented Sep 13, 2020 at 18:14
  • 1
    There is no reason in using map here. map takes a collection and a function to apply to each element an return a new collection of the same size. Whereas, you actually want to reduce all the elements in the collection into a single element, that is what folding does. Commented Sep 13, 2020 at 18:16

1 Answer 1

1

Following works but note that it is not safe, it throws exception if arr contains element/s that does not have exact 2 elements. You should add additional missing cases in pattern match as per your use case

val result = arr.fold(Array(1, 0)) {
  case (Array(x1, x2), Array(y1, y2)) => Array(x1 * y1, x2 + y2)
}

Update

As @Luis suggested, if you make your original Array[Array] to Array[Tuple], another implementation could look like this

val arr = Array((2, 1), (3, 1), (4, 1))

val (prdArr, sumArr) = arr.unzip
val result           = (prdArr.product, sumArr.sum)

println(result) // (24, 3)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for suggestion, yes tuple fits betters there. This works (y) !

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.