【问题标题】:How to determine if an array has consecutive integers and if so, how many?如何确定一个数组是否有连续的整数,如果有,有多少?
【发布时间】:2017-05-14 14:30:58
【问题描述】:

我还是 Scala 的新手,但我试图确定一个数组是否有任何连续的整数,如果有,那么它有多少。这是我到目前为止所拥有的,但我还没有开始工作。

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,以及连续整数的个数或零。

【问题讨论】:

  • Array(1, 2, 3, 5, 6, 7, 9, 10) 中包含多少个连续整数?
  • @m-z 好问题。此函数的用例中只有 5 个数字。真的在这种情况下,我想要获得更大的连续数字集。所以输出将是true, 3。也许这不是实现我的目标的方法

标签: arrays scala


【解决方案1】:
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)

【讨论】:

    【解决方案2】:

    如果您需要检查始终以 1 开头且始终从第一个元素开始的整数:

    scala> List(1,2,3,4,5,8,9).zipWithIndex.takeWhile(x => x._1 == x._2 + 1).size
    res45: Int = 5
    

    *您可以使用res45 == 0查看您的情况,不需要额外的Boolean

    或者,如果您想要任何具有连续整数的子序列中的所有元素计数:

    case class Counter(v: Int, counters: List[Int], prevElem: Int)   
    
    def conseq(l: List[Int]) = {
       val r = l.tail.foldLeft(Counter(0,List.empty,l.head)){(acc, el) =>
          if (el - acc.prevElem == 1) Counter(acc.v + 1, acc.counters, el) 
          else if (acc.v == 0) acc.copy(prevElem = el)
          else Counter(0, acc.v + 1 :: acc.counters, el)
       }
       r.counters.reverse ++ List(r.v).filter(0!=)//linear time; you might consider Vector or something instead of List
    }
    
    scala> conseq(List(1,2,3,4,100,105,106,107))
    res44: List[Int] = List(4, 3)
    

    您还可以收集每个子序列的初始值(如上一个示例中的 1 和 105)及其索引(如上一个示例中的 0 和 5) - 您也可以在 Counter 中进行。

    【讨论】:

    • 也许你可以包含Counter的定义?
    【解决方案3】:

    测量最长连续整数的长度,类似于当前的答案,但作为简单的尾递归实现:

      def countConsecutive(s: Seq[Int]) = {
        @tailrec
        def countConsecutiveRecurse(maxLen: Int, s: Seq[Int], currLen: Int, currVal: Int): Int = s match {
          case Seq() => maxLen max currLen
          case head +: tail =>
            if (head == currVal + 1) countConsecutiveRecurse(maxLen, tail, currLen + 1, head)
            else countConsecutiveRecurse(maxLen max currLen, tail, 1, head)
        }
    
        countConsecutiveRecurse(0, s, 0, 0)
      }
    

    【讨论】:

      【解决方案4】:

      以下解决方案将尝试识别连续整数的最长延伸,而不仅仅是存在多少连续对。对于后一个问题,@jwvh 的解决方案很棒。

      这个想法是有一个 Result 类型,你 foldLeft 并相应地更新:

      case class Result(prev: Int, curMax: Int = 0, max: Int = 0) {
         /* process takes the next int and updates the result up to that point */
         def process(n: Int) = {
            val newRunningMax = if(n==(prev+1)) curMax + 1 else 0
            Result(n, newRunningMax, Math.max(max, newRunningMax))
         }
      }
      
      def findLongestConsecutiveSeq(data: Array[Int]): (Boolean, Int) = {
         require(data.nonEmpty, "Only works with non empty arrays") 
         val res = data.tail.foldLeft(Result(data.head))( (p,n) => p.process(n) )   
         if(res.max > 0) (true, res.max + 1) // max = consecutive pairs (+1 for length)
         else (false, 0) 
      }
      

      在 REPL 中测试:

      findLongestConsecutiveSeq(Array(1,2,3,4,5,8,9))
      res1: (Boolean, Int) = (true, 5)
      
      findLongestConsecutiveSeq(Array(1,3,3,4,5,8,9))
      res2: (Boolean, Int) = (true, 3)
      
      findLongestConsecutiveSeq(Array(3,2,2,2))
      res3: (Boolean, Int) = (false, 0)
      
      findLongestConsecutiveSeq(Array(0,1,2,3,4,5,6,6,6,6,7,8,9,10,11,12,13))
      res4: (Boolean, Int) = (true, 8)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-06
        • 1970-01-01
        • 1970-01-01
        • 2020-12-24
        • 2016-08-07
        • 2014-02-23
        相关资源
        最近更新 更多