wipman wipman - 8 months ago 35
Scala Question

Calculation on consecutive array elements

I have this:

val myInput:ArrayBuffer[(String,String)] = ArrayBuffer(

I would like to calculate the duration between each two consecutive timestamps from
and retrieve those like the following:

val myOutput = ArrayBuffer(

This is a paired evaluation, which led me to think something with
might do the trick, but after giving this a little more thought, I could not come up with a solution.

I have already put something together with some
for loops
, but this does not seem as clean and concise as it could be. I would appreciate if somebody had a better option.


You can use zip and sliding to achieve what you want. For example, if you have a collection

scala> List(2,3,5,7,11)
res8: List[Int] = List(2, 3, 5, 7, 11)

The list of differences is res8.sliding(2).map{case List(fst,snd)=>snd-fst}.toList, which you can zip with the original list.

scala> res8.zip(res8.sliding(2).map{case List(fst,snd)=>snd-fst}.toList)
res13: List[(Int, Int)] = List((2,1), (3,2), (5,2), (7,4))