Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to check if a list has no gaps

I just want a function that returns true if all the elements of a List[Integer] follow each other, i.e.

noGaps(List(3,4,5)) // true
noGaps(List(4,3,5)) // false
noGaps(List(3,4,6)) // false

I have something that works but it's a bit verbose - what's the most elegant solution?

like image 523
Luigi Plinge Avatar asked Dec 13 '22 10:12

Luigi Plinge


1 Answers

How about this?

def noGaps(xs: Seq[Int]) =
  xs.size < 2 || xs.sliding(2).forall { case Seq(x, y) => y == x + 1 }
like image 104
Jean-Philippe Pellet Avatar answered Dec 14 '22 23:12

Jean-Philippe Pellet