dumm3rjung3
dumm3rjung3

Reputation: 129

calculate average from values in map in scala

I have a map that represents a gradebook where the key is the grade and the value is the number of students who achieved that grade.

my map looks like this:

grades = Map("1" -> 0, "2" -> 0, "3" -> 0, "4" -> 0, "5" -> 0)

then i read the values for the keys from a list of students with their grades, filling the 0s with values.

what i want to do now is calculate the average grade:

val avg = grades.foreach{case (k,v) => k * v} / grades.foldLeft(0)(_+_._2)

but the problem is that

grades.foreach{case (k,v) => k * v}

only returns ().

Upvotes: 3

Views: 2098

Answers (1)

Zahiro Mor
Zahiro Mor

Reputation: 1718

try: (there are other methods to do this - I'm trying to stick with your original flow)

val avg =  grades.map{case (k,v) => k.toInt * v}.sum 
         / grades.foldLeft(0)(_+_._2).toFloat

my alterations to your code: 1. use map and not foreach 2. cast k into integer 3. divide by float to get float answer

Upvotes: 4

Related Questions