'Dynamic sliding window in Scala

Suppose, I have a log file of events (page visits) with a timestamp. I'd like to group events into sessions where I consider that events belong to the same session when they are not further than X minutes from each other.

Currently, I ended up with this algorithm.

val s = List(1000, 501, 500, 10, 3, 2, 1) // timestamps
val n = 10 // time span

import scala.collection.mutable.ListBuffer

(s.head +: s).sliding(2).foldLeft(ListBuffer.empty[ListBuffer[Int]]) {
  case (acc, List(a, b)) if acc.isEmpty =>
    acc += ListBuffer(a)
    acc
  case (acc, List(a, b)) =>
    if (n >= a - b) {
      acc.last += b
      acc
    } else {
      acc += ListBuffer(b)
      acc
    }
}

The result

ListBuffer(ListBuffer(1000), ListBuffer(501, 500), ListBuffer(10, 3, 2, 1))

Is there any better/functional/efficient way to do it?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source