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

被折叠的 条评论
为什么被折叠?



