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 t开发者_JAVA百科hat works but it's a bit verbose - what's the most elegant solution?
How about this?
def noGaps(xs: Seq[Int]) =
xs.size < 2 || xs.sliding(2).forall { case Seq(x, y) => y == x + 1 }
def noGaps(xs: Seq[Int]) = xs.isEmpty||xs.tail == xs.map(_+1).init
You can make it explicit that you compare the List
to a Range
:
def noGaps(l: Seq[Int]): Boolean =
l.isEmpty || l.sameElements(l.head to l.last)
Note that, although elegant, this is slightly less efficient than the sliding solution, due to l.last
which is O(n)
. If n
is the size of the list and i
the first element for which there is a gap (or n
if no gap), then the sliding solution would be performed in i
steps whereas this one is performed in n + i
steps.
精彩评论