undisp
undisp

Reputation: 721

Calculate average and remove from list in Scala

I am on my first week with Scala and struggling with the way the code is written in this language.

I am trying to write a function that determines the average number in a list and removes the values below that average. For example:

I have this list:

List[(String, Int)] = List(("A", 1), ("B", 1), ("C", 3), ("D", 2), ("E", 4))

The result should be 2.2.

So the function should also remove the entries ("A", 1), ("B", 1) and ("D", 2) because they are below the average.

Can anyone help me?

Upvotes: 1

Views: 4324

Answers (3)

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23329

You can calculate the average of the second elements of the list of tuples, you don't need to do the sum yourself because Scala has a builtin function for that. First we need to transform the list of tuples to a list of Int values, we can do that using the map function as shown below

val average = list.map(_._2).sum/list.size.toDouble

Now you have the average, you can filter your list based on its value

val newList = list.filter(_._2  < average)

Note that we didn't remove anything from the list, we created a new one with filtered elements

Upvotes: 4

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

You can do:

val sum = list.map(_._2).sum
val avg: Double = sum / list.size.toDouble

val filtered = list.filter(_._2 > avg)

Note this is traversing the list twice, once for summing and once for filtering. Another thing to note is that Scala List[T] is immutable. When you filter, you're creating a new List object with the filtered data.

Upvotes: 1

Regis Blanc
Regis Blanc

Reputation: 549

val average = list.map(_._2).sum / list.size.toDouble
list.filter(p => p._2 >= average)

You need to cast to Double, else average would be cast to an Int and be imprecise. The filter only keeps the element greater than the average.

Upvotes: 1

Related Questions