Peyam pc
Peyam pc

Reputation: 11

Add sum of values of two lists into new one in scala

v1 = [1,2,3,4]
v2 = [1,2,3,4,5]

I need the sum of these lists: [2,4,6,8,5]

And is there any way to print elements that executes a+b= c , where c is for example 8 ?

How can I do that in scala?

Upvotes: 0

Views: 2011

Answers (2)

elm
elm

Reputation: 20405

A similar approach to Ben's, using a for comprehension,

for ( (a,b) <- v1.zipAll(v2, 0, 0) if a+b == 8 ) yield (a,b)

which delivers those (zipped) pairs of values whose sum is 8.

Upvotes: 0

Ben Reich
Ben Reich

Reputation: 16324

You can use zipAll to zip the lists together. That method takes in two extra arguments that represents the element to use in case one list is longer than the other, and vice versa. Since you are adding the lists, you should use the additive identity 0. Then you can simply map over the generated list of tuples:

val v1 = List(1, 2, 3, 4)
val v2 = List(1, 2, 3, 4, 5)
v1.zipAll(v2, 0, 0).map { case (a, b) => a + b }

You can read the documentation of zipAll in the documentation of IterableLike. The most relevant part:

Returns a iterable collection formed from this iterable collection and another iterable collection by combining corresponding elements in pairs. If one of the two collections is shorter than the other, placeholder elements are used to extend the shorter collection to the length of the longer.

If you're looking to print out certain elements, you might choose to filter instead of map, and then use foreach:

v1.zipAll(v2, 0, 0).filter { 
    case(a, b) => a + b == 8 
}.foreach { 
    case(a, b) => println(s"$a+$b=8") 
}

Or just a foreach with more interesting case statements:

v1.zipAll(v2, 0, 0).foreach { 
    case(a, b) if a + b == 8  => println(s"$a+$b=8")
    case _ => 
}

Or you could use collect, and ignore the return value:

v1.zipAll(v2, 0, 0).collect { 
    case(a, b) if a + b == 8 => println(s"$a+$b=8") 
}

You might want to read some introductory text to the Scala collections library, like the one in the docs.

Upvotes: 6

Related Questions