【问题标题】:How to find two successive and same values in a Stream?如何在流中找到两个连续且相同的值?
【发布时间】:2018-12-16 00:48:53
【问题描述】:

如何在Stream 中找到两个连续且相同的值并返回此“重复值”:

def succ: Stream[Int] => Int = str => ...

例如Stream(1, 2, 4, 3, 5, 5, 2, 2) 将导致5

如何做到这一点?

【问题讨论】:

    标签: scala stream duplicates return scala-streams


    【解决方案1】:

    您可以混合使用Stream.slidingStream.collectFirst

    def succ(stream: Stream[Int]): Option[Int] =
      stream.sliding(2).collectFirst { case Stream(x, y) if x == y => x }
    

    产生:

    Stream(1, 2, 4, 3, 5, 5, 2, 2)
      .sliding(2) // Stream(Stream(1, 2), Stream(2, 4), Stream(4, 3), ...
      .collectFirst { case Stream(x, y) if x == y => x } // Some(5)
    

    None,如果没有连续的元素共享相同的值。


    根据您的评论,为了在没有连续元素共享相同值时返回0 而不是None,您可以在管道末尾应用.getOrElse(0)

    def succ(stream: Stream[Int]): Int =
      stream.sliding(2).collectFirst { case Stream(x, y) if x == y => x }.getOrElse(0)
    

    【讨论】:

    • 如果没有连续的值,它返回0。如果有这样的值,它应该直接返回它。
    【解决方案2】:

    用尾部压缩流是另一种处理单元素流的方法。明确处理空流:

    def succ: Stream[Int] => Int = {
      case Stream() => 0
      case str =>
        str.zip(str.tail).
        find { case (l, r) => l == r }.
        map { case (x, _) => x }.
        getOrElse(0)
    }
    

    【讨论】:

      【解决方案3】:

      使用简单递归怎么样?

      def succ: Stream[Int] => Int = {
        def rec(x: Int, xs: Stream[Int]): Int = {
          if (x == xs.head) x
          else rec(xs.head, xs.tail)
        }
      
        (str: Stream[Int]) => rec(str.head, str.tail)
      }
      

      如果没有找到后续重复项,这将不起作用,因为您必须将返回类型更改为 Option[Int] 并添加一些额外的检查。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-18
        • 1970-01-01
        • 2019-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多