P11 (*) Modified run-length encoding.

来源:互联网 发布:阿里云账户注销 编辑:程序博客网 时间:2024/05/06 22:28
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)  根据条件将列表分成两部分
//11def 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)
参考答案
0 0
原创粉丝点击