scala-problem11-15

* 声明*
该系列文章来自:http://aperiodic.net/phil/scala/s-99/
大部分内容和原文相同,加入了部分自己的代码。
如有侵权,请及时联系本人。本人将立即删除相关内容。

P11 (*) Modified run-length encoding.

要求

Modify the result of problem P10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as (N, E) terms.

Example:

scala> encodeModified(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
res0: List[Any] = List((4,'a), 'b, (2,'c), (2,'a), 'd, (4,'e))

方案

  • (1) P10中返回的List元素类型是二元组(count,element),对list执行map判断 t._1是否为1
def encodeModified[T](list: List[T]): List[Any] =
    encode(list).map(e => if (e._1 == 1) e._2 else e)

P12 (**) Decode a run-length encoded list.

要求

Given a run-length code list generated as specified in problem P10, construct its uncompressed version.

Example:

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

方案

  • (1) List.fill + flatMap
def decode[T](list: List[(Int, T)]): List[T] =
    list.flatMap(e => List.fill(e._1)(e._2))

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

要求

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))

方案

  • (1) span + 递归
def encodeDirect[T](list: List[T]): List[(Int, T)] = {
    if (list == Nil)
        return List()
    else {
        val (packed, tail) = list.span(_ == list.head)
        return (packed.length, packed.head) :: encodeDirect(tail)
    }
}

P14 (*) Duplicate the elements of a list.

要求

Example:

scala> duplicate(List('a, 'b, 'c, 'c, 'd))
res0: List[Symbol] = List('a, 'a, 'b, 'b, 'c, 'c, 'c, 'c, 'd, 'd)

方案

def duplicate[T](list: List[T]): List[T] = {
    list.flatMap { e => List(e, e) }
}

P15 (**) Duplicate the elements of a list a given number of times.

要求

Example:

scala> duplicateN(3, List('a, 'b, 'c, 'c, 'd))
res0: List[Symbol] = List('a, 'a, 'a, 'b, 'b, 'b, 'c, 'c, 'c, 'c, 'c, 'c, 'd, 'd, 'd)

方案

def duplicateN[T](n: Int, list: List[T]): List[T] = {
    list.flatMap { e => List.fill(n)(e) }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值