Having a collection of tuples I would like to check if a given integer element in all the tuples is having values in consecutive order. For simplicity it can be assumed that the tuples are sorted in ascending order by that element.
For example considering the first element of all tuples in this array should return false (4, 8, 9, 10, 13):
val a = List((4,2), (8,1), (9,4), (10,2), (13,1))
While considering the first element of all the tuples in this array should return true (8, 9, 10, 11, 12):
val b = List((8,2), (9,1), (10,4), (11,2), (12,1))
Using List as a collection with pattern matching I can do the check using the pattern matching as presented below:
def consecutive(l: List[(Int, Int)], last: Option[Int] = Option.empty): Boolean =
l match {
case h :: t => {
if (last.isEmpty || (last.isDefined && h._1 == last.get + 1))
consecutive(t, Option(h._1))
else false
}
case Nil => true
}
Is there an easier way to accomplish it?