0

I am very new to Scala but I was wondering if anyone could help me.

I have the following data set in this format: Map[String, List[(Int, String, Float)]]

Data Sample:

Education Route (GU),1:University Of Strawberry:0.65f,2:City Of Cabbage College - Riverside Camp:1.4f,3:School of Sims:3.9f,4:Science Centre:0.7f,5:University of Grapes:2.4f,6:The Mushroom Library:1.9f,7: School Of Fruit:0.9f,8:Royal Conservatoire Of Melons:0.75f,9:GU:0.6f`

I am trying to get the average total distance and average number of stages of all routes - I have the following from a previous excercise :

def average(ls:List[Int]):Float = {
  sum(ls)/length(ls)
}

println(average(list1))

I appreciate this is a more simplistic example but any help would be much appreciated. I also did think about the approach of adding the values up then dividing by the number of routes?

Bob
  • 1,351
  • 11
  • 28
  • Does this answer your question? [How to sum number of Ints and Number of Floats within a List - Scala](https://stackoverflow.com/questions/61232542/how-to-sum-number-of-ints-and-number-of-floats-within-a-list-scala) – Bob Apr 15 '20 at 22:03
  • I have had a look at that question and it looks like its adding the total distances and routes whereas I'm looking for the method to calculate average of these? – uncharted2020 Apr 15 '20 at 22:22

1 Answers1

0

If you want to just write an average method, this can be done with one iteration.

UPDATE:

def average[T](ls: List[T])(implicit num: Numeric[T]): Float = {
  val (sum, length) =
    ls.foldLeft((0.0f, 0))({ case ((s, l), x) => (num.toFloat(x) + s, 1 + l) })
  sum / length
}

val map = Map[String, List[(Int, String, Float)]](
  "Education Route (GU)" -> List(
    (1, "University Of Strawberry", 0.65f),
    (2, "City Of Cabbage College - Riverside Camp", 1.4f),
    (3, "School of Sims", 3.9f),
    (4, "Science Centre", 0.7f),
    (5, "University of Grapes", 2.4f),
    (6, "The Mushroom Library", 1.9f),
    (7, "School Of Fruit", 0.9f),
    (8, "Royal Conservatoire Of Melons", 0.75f),
    (9, "GU", 0.6f)
  )
)

val distances = map.mapValues(_.map(_._3)).getOrElse("Education Route (GU)", List.empty)
val steps = map.mapValues(_.map(_._1)).getOrElse("Education Route (GU)", List.empty)

val averageDistance = average[Float](distances)
val averageSteps = average[Int](steps)
println(s"Average distance: $averageDistance")
println(s"Average steps: $averageSteps")

Scastie sample is here

Bob
  • 1,351
  • 11
  • 28
  • When I try to run this it throws a 'type mismatch' error: Error:(100, 28) type mismatch; found : List[(String, List[(Int, String, Float)])] required: List[Int] – uncharted2020 Apr 15 '20 at 23:46
  • @uncharted2020 you are passing wrong data structure to a list. – Bob Apr 16 '20 at 10:54