user2492364
user2492364

Reputation: 6693

scala deal with string and do accumulative

I have variable:

val list= rows.sortBy(- _._2).map{case (user , list) => list}.take(20).mkString("::")  

the result println(list) should be:

60::58::51::48::47::47::45::45::43::43::42::42::42::41::41::41::40::40::40::39

And now I have to deal with these numbers (like histogram concept)

If I set the break is 10, it should divide the max number (60) by 10 and make 6 buckets:

And then I have to save with 2 variables x and y :

x:  0~10::10~20::20~30::30~40::40~50::50~60
y:  0::0::0::4::13::3

How can I do this?

Upvotes: 0

Views: 61

Answers (1)

Justin Pihony
Justin Pihony

Reputation: 67065

val actualList = list.split("::").map(_.toInt).toList
val step = 10
val steps = step to actualList.max by step
//for each step, output a count of all items in the list that are 
//between the current step and currentStep - stepVal
val counts = steps.map(x=>actualList.count(y=>y <= x && y > x - step))
val stepsAsString = steps.map(x=>s"${x-step}~$x")

And you can map them too:

steps.zip(counts).toMap

Note that this could be made more performant if the list were sorted first, but I wouldn't worry about tuning unless you need it

Upvotes: 1

Related Questions