scalatuplesaccumulator

Count how many times numbers from a list occur in a list of tupled intervals in Scala


Say I have a list of tuples:

val ranges= List((1,4), (5,8), (9,10))

and a list of numbers

val nums = List(2,2,3,7,8,9)

I want to make a map from tuple in ranges to how many times a given number from nums fall into the interval of that tuple.

Output:

Map ((1,4) -> 3, (5,8) -> 2, (9,10) -> 1)

What is the best way to go about it in Scala

I have been trying to use for loops and keeping a counter but am falling short.


Solution

  • Something like this:

    val ranges = List((1, 4), (5, 8), (9, 10))
    val nums = List(2, 2, 3, 7, 8, 9)
    
    val occurences = ranges.map { case (l, r) => nums.count((l to r) contains _) }
    val map = (ranges zip occurences).toMap
    
    println(map) // Map((1,4) -> 3, (5,8) -> 2, (9,10) -> 1)
    

    Basically it first calculates the number of occurrences, [3, 2, 1]. From there it's easy to construct a map. And the way it calculates the occurrences is: