P11 (*) Modified run-length encoding.

本文介绍了一种将列表中元素进行编码修改的方法,针对具有重复元素的列表,仅保留重复计数及唯一元素。通过示例展示如何使用Scala实现此功能,包括列表拆分、条件判断及结果映射等关键步骤。

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

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))
 
spanList通过递归将列表拆分成多个元素相同的列表,
(takes,lefts)=curList span(_==curList.head)  根据条件将列表分成两部分
 
//11
def encodeModified[A](ls: List[A]) =  {
    def spanList[A](curList:List[A]):List[List[A]]={
      if(curList.isEmpty) List(List())
      else{
        val list=Nil
        val (takes,lefts)=curList span(_==curList.head)
        if(lefts==Nil) List(takes)
        else List(takes):::spanList(lefts)
       }
    }

  spanList(ls).map(e=> if(e.length>1){(e.length,e.head)} else{e.head} )
}

def main(args: Array[String])= {
  println(encodeModified(List(1,1,2,2,3,4,4,5,7)))
}

结果
List((2,1), (2,2), 3, (2,4), 5, 7)
 
参考答案
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值