要计算列表中的连续字符吗?

问题描述 投票:0回答:2

我想创建一个scala方法来计算值相同的连续字符的数量。所以我有这个清单:

列表( '一个', 'A', 'B')

并且我想返回类似List(('a',2),'b',1)之类的东西-因为两个字符之间的值相同。我对此一无所获,但收效甚微:

  def recursivelyCompressList(list: List[(Char, Int)], newString: List[(Char, Int)]): List[(Char, Int)] = {

    list match {
      case Nil => newString
      case s :: tail => {
        if (tail.nonEmpty && s._1 == tail.head._1) {
          recursivelyCompressList(tail, newString :+ (s._1, s._2 + 1))
        } else {
          recursivelyCompressList(tail, newString :+ s)
        }

      }
      case _ => newString

    }

  }

感谢您提供任何指导。

scala recursion
2个回答
0
投票

这应该有效。我希望代码是不言自明的,但是如果您有任何疑问,请不要怀疑。

def compressList[T](list: List[T]): List[(T, Int)] = {
  @annotation.tailrec
  def loop(remaining: List[T], currentValue: T, currentCount: Int, acc: List[(T, Int)]): List[(T, Int)] =
    remaining match {
      case Nil =>
        ((currentValue -> currentCount) :: acc).reverse

      case t :: tail =>
        if (t == currentValue)
          loop(
            remaining = tail,
            currentValue,
            currentCount + 1,
            acc
          )
        else
          loop(
            remaining = tail,
            currentValue = t,
            currentCount = 1,
            (currentValue -> currentCount) :: acc
          )
    }

  list match {
    case Nil =>
      Nil

    case t :: tail =>
      loop(
        remaining = tail,
        currentValue = t,
        currentCount = 1,
        acc = List.empty
      )
  }
}

您可以这样使用:

compressList(List.empty[Char])
// res: List[(Char, Int)] = List()

compressList(List('a', 'b'))
// res: List[(Char, Int)] = List(('a', 1), ('b', 1))

compressList(List('a', 'a', 'b'))
// res: List[(Char, Int)] = List(('a', 2), ('b', 1))

compressList(List('a', 'a', 'b', 'b', 'b', 'a', 'c'))
// res: List[(Char, Int)] = List(('a', 2), ('b', 3), ('a', 1), ('c', 1))

0
投票

使用takeWhiledropWhile

scala> val list = List('a', 'a', 'b')

list: List[Char] = List('a', 'a', 'b')


scala>
  def count(xs: List[Char]): List[(Char, Int)] = {
    if (xs.isEmpty) Nil
    else {
      (xs.head, xs.takeWhile(_ == xs.head).length) :: count(xs.dropWhile(_ == xs.head))
    }
  }
defined function count



scala>   val result = count(list)
result: List[(Char, Int)] = List(('a', 2), ('b', 1))



scala>   println(s"Result: $result")
Result: List((a,2), (b,1))

连续计数

def count(xs: List[Char]): List[(Char, Int)] = if (xs.isEmpty) Nil
 else (xs.head, xs.takeWhile(_ == xs.head).length) :: count(xs.dropWhile(_ == xs.head))
© www.soinside.com 2019 - 2024. All rights reserved.