wipman wipman - 3 months ago 10
Scala Question

Calculation on consecutive array elements

I have this:

val myInput:ArrayBuffer[(String,String)] = ArrayBuffer(
(a,timestampAStr),
(b,timestampBStr),
...
)


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

val myOutput = ArrayBuffer(
(a,durationFromTimestampAToTimestampB),
(b,durationFromTimestampBToTimestampC),
...
)


This is a paired evaluation, which led me to think something with
foldLeft()
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
and
.indices
, but this does not seem as clean and concise as it could be. I would appreciate if somebody had a better option.

Answer

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))