Elemental sum of arrays in Scala

How to calculate the elementary sums of arrays?

val a = new Array[Int](5)
val b = new Array[Int](5)
// assign values
// desired output: Array -> [a(0)+b(0), a(1)+b(1), a(2)+b(2), a(3)+b(3), a(4)+b(4)]

a.zip(b).flatMap(_._1+_._2)

Missing parameter type for advanced function

+6
source share
3 answers

Try:

a.zip(b).map { case (x, y) => x + y }
+11
source

When you use an underscore as a substitute in a function definition, it can only appear once (for each position of the function argument, that is, but in this case it flatMapaccepts Function1, so there is only one). If you need to refer to an argument more than once, you cannot use the placeholder syntax - you need to specify a name argument.

, .map { case (x, y) => x + y } , , , :

scala> (a, b).zipped.map(_ + _)
res5: Array[Int] = Array(0, 0, 0, 0, 0)

zipped - , , map, Function2, , , , (a, b). , , , , Function2 , , .

+10
// one D Array    
val x = Array(1, 2, 3, 40, 55)    
val x1 = Array(1, 2, 3, 40, 55)    
x.indices.map(i=>x(i)+ x(i) )  

// TWo D Array    
val x1= Array((3,5), (5,7))    
val x = Array((1,2), (3,4))    
x.indices.map(i=>( x(i)._1 + x1(i)._1, x(i)._2 + x1(i)._2))
-1
source

Source: https://habr.com/ru/post/1626371/


All Articles