有一个元组的集合,我想检查所有元组中的给定整数元素是否具有连续顺序的值。为简单起见,可以假定元组由该元素按升序排序。
例如,考虑到此数组中所有元组的第一个元素应返回false
(4、8、9、10、13):
val a = List((4,2), (8,1), (9,4), (10,2), (13,1))
考虑此数组中所有元组的第一个元素时,应返回true
(8、9、10、11、12):
val b = List((8,2), (9,1), (10,4), (11,2), (12,1))
使用List
作为具有模式匹配的集合,我可以使用如下所示的模式匹配进行检查:
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
}
有没有更简单的方法来完成它?
答案 0 :(得分:2)
您可以尝试使用sliding
:
def consecutive(s: Seq[(Int, Int)]): Boolean = s match {
case Seq() => true
case Seq(_) => true
case _ => s.sliding(2).forall { case Seq((x, _), (y, _)) => x + 1 == y }
}
scala>consecutive(b)
res5: Boolean = true
consecutive(a)
res7: Boolean = false
或者您也可以尝试以下定义:
def consecutive(s: Seq[(Int, Int)]): Boolean =
if (s.isEmpty) true
else (s zip s.tail) forall { case ((x,_), (y,_)) => x + 1 == y}
答案 1 :(得分:2)
这是使用foldLeft
def consecutive(list: List[(Int, Int)]): Boolean = {
list.map(_._1) match {
case first :: second :: tail =>
val (_, isConsecutive) =
(second :: tail).foldLeft((first, true)) { case ((previous, previousWasConsecutive), next) =>
(next, next - previous == 1 && previousWasConsecutive)
}
isConsecutive
case _ => true
}
}
输出
consecutive(Nil) // res0: Boolean = true
consecutive(List((1,2))) // res1: Boolean = true
consecutive(List((4,2), (8,1), (9,4), (10,2), (13,1))) // res2: Boolean = false
consecutive(List((8,2), (9,1), (10,4), (11,2), (12,1))) // res3: Boolean = true