0

I have a method that collect the consecutive number with the difference of no more than some number (2 in my example). This code is working just fine but it does zipping every time it is called, so I wonder if there is any better solution to this thanks.

def myGrouper(sortedData: Seq[Int], maxDif: Int): Seq[Seq[Int]] = sortedData match {
  case Nil => Nil
  case _ =>
    val (grouped, rest) = sortedData.zipWithIndex.span{
    case (num, idx) =>
      if (idx > 1) Math.abs(sortedData(idx-1) - num) <= maxDif
      else true
  }
    Seq(grouped.map(_._1)) ++ myGrouper(rest.map(_._1), maxDif)
}

val myList = Seq(1, 2, 3, 7, 8, 10, 15, 17, 19)
val maxDif = 2
println(myGrouper(myList, maxDif))

Below is the result from running this code

myList: Seq[Int] = List(1, 2, 3, 7, 8, 10, 15, 17, 19)
maxDif: Int = 2
List(List(1, 2, 3), List(7, 8, 10), List(15, 17, 19))
res0: Unit = ()
  • I'm voting to close this question as off-topic because it belongs on [Code Review](http://codereview.stackexchange.com) – Yuval Itzchakov Jul 29 '16 at 11:15
  • 1
    Possible duplicate of [How to extend a Scala list to enable slicing not by explicit position but by given predicate/condition](http://stackoverflow.com/questions/21800041/how-to-extend-a-scala-list-to-enable-slicing-not-by-explicit-position-but-by-giv) – The Archetypal Paul Jul 29 '16 at 12:32
  • 1
    Actaully, this is an exact duplicate of this: http://stackoverflow.com/questions/19605344/split-list-in-scala-based-on-diff-between-neighbouring-elements – The Archetypal Paul Jul 29 '16 at 12:34

0 Answers0