如何确定数组是否具有连续的整数,如果有,则有多少个? [英] How to determine if an array has consecutive integers and if so, how many?
本文介绍了如何确定数组是否具有连续的整数,如果有,则有多少个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Scala还是个新手,但是我试图确定一个数组是否有任何连续的整数,如果有,那么它有多少个整数。这是我到目前为止的内容,但是我还没有开始。
I am still pretty new at Scala, but I am trying to determine if an array has any consecutive integers, and if it does then how many does it have. Here is what I have so far, but I haven't got it working yet.
def isConsecutive(seq: Array[Int]): (Boolean, Int) = {
var arr: Array[Int] = Array[Int]()
for((v, i) <- seq.zipWithIndex) {
if (i < seq.length()) {
if (v + 1 == seq(i + 1)) {
arr = arr :+ v
}
}
}
var res = if (arr.length() < 1) true else false
return (res, arr.length())
}
我只想返回一个布尔值,用于判断数组是否具有连续的整数,即1,2,3,
I just want to return a Boolean for whether or not the array has consecutive integers, i.e. 1,2,3, and the number of consecutive integers or zero.
推荐答案
def isConsecutive(seq: Array[Int]): (Boolean, Int) = {
val count = seq.sliding(2).count(a => a(0)+1 == a(1))
(count > 0, count)
}
并对其进行测试:
scala> isConsecutive(Array(3,5,8,99))
res0: (Boolean, Int) = (false,0)
scala> isConsecutive(Array(3,4,5,8,99))
res1: (Boolean, Int) = (true,2)
scala> isConsecutive(Array(3,4,5,98,99))
res2: (Boolean, Int) = (true,3)
这篇关于如何确定数组是否具有连续的整数,如果有,则有多少个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文