'Summation/multiplication of a list of tuples
I'm trying to figure out a simple operation that takes a list of (Int, Int)
tuples and multiplies the tuples internally and then sums those results. Example:
val list = ((9, 4), (1, 5), (4, 6))
Would evaluate to (36, 5, 24)
, which would then evaluate to 65. I was thinking I could take the list then pattern match for a single tuple, not unlike:
list.map{
case x => x(0)._1 * x(0)._2
}
But this would just take the first tuple and multiply each component. I suppose I could do an aggregation, but I don't know how I'd approach that.
Solution 1:[1]
((9, 4), (1, 5), (4, 6)) is not a list but rather a tuple of tuples
val list = List[(Int, Int)]((9, 4), (1, 5), (4, 6))
val result = list.map{ case (a, b) => a * b }.sum
Solution 2:[2]
First take all tuples and multiply the components. This can be done by using a map
which will process each tuple individually. After that call sum
on the resulting list which will sum all elements together.
val res = list.map(x => x._1 * x._2).sum
The case
is not necessary here and you can't use (0)
since the elements of the list is tuples, not lists themselves.
Solution 3:[3]
You can use ListBuffer
way as
val list = ((9, 4), (1, 5), (4, 6))
val listBuffer = new ListBuffer[Int]
for(tuple <- list.productIterator){
val (a, b) = tuple.asInstanceOf[Tuple2[Int, Int]]
listBuffer += a * b
}
which should give you
ListBuffer(36, 5, 24)
and calling sum
function as listBuffer.sum
should give you 65
Solution 4:[4]
Here is another approach using collect
on a list
scala> val list = List((9, 4), (1, 5), (4, 6))
list: List[(Int, Int)] = List((9,4), (1,5), (4,6))
scala> list.collect{
case ele => ele._1 * ele._2
}.sum
res1: Int = 65
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Denis Makarenko |
Solution 2 | Shaido |
Solution 3 | Ramesh Maharjan |
Solution 4 | Puneeth Reddy V |