P13 (**) Run-length encoding of a list (direct solution).

本文介绍了一种直接实现的 Run-Length 数据压缩方法,通过 Scala 语言展示了如何不借助其他辅助函数来完成这一任务。提供了两种不同的实现方式,一种是递归地移除重复元素并计算长度,另一种则是使用 span 函数进行分割。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Implement the so-called run-length encoding data compression method directly. I.e. don't use other methods you've written (like P09's pack); do all the work directly.

Example:

scala> encodeDirect(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
res0: List[(Int, Symbol)] = List((4,'a), (1,'b), (2,'c), (2,'a), (1,'d), (4,'e))


//13
  def encodeDirect[A](ls:List[A]):List[(Int,A)]={
      if(ls==Nil) Nil
      else {
        val l = ls.dropWhile(_ == ls.head)
        List((ls.length - l.length, ls.head)) ::: encodeDirect(l)
      }
  }

  def main(args: Array[String])= {
    println(encodeDirect(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e)))
  }
}

上面是我自己想的方法


参考答案

def encodeDirect[A](ls: List[A]): List[(Int, A)] =
    if (ls.isEmpty) Nil
    else {
      val (packed, next) = ls span { _ == ls.head }
      (packed.length, packed.head) :: encodeDirect(next)
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值