P19 (**) Rotate a list N places to the left.
来源:互联网 发布:电脑怎么申请淘宝达人 编辑:程序博客网 时间:2024/06/06 03:39
Examples:
scala> rotate(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))res0: List[Symbol] = List('d, 'e, 'f, 'g, 'h, 'i, 'j, 'k, 'a, 'b, 'c)scala> rotate(-2, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))res1: List[Symbol] = List('j, 'k, 'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i)
//19def rotate[A](n:Int,ls:List[A]):List[A]={ var list=ls if(n>0){ for(i<-0 to n-1) { list = list ::: List(list.head) list = list.drop(1) } list }else{ for(i<- n+1 to 0) { list = List(list.last):::list list = list.dropRight(1) } list }}
当然直接用drop和take好一些
def rotate2[A](n:Int,ls:List[A]):List[A]={ if(n>0){ ls.drop(n):::ls.take(n) } else{ ls.takeRight(-n):::ls.dropRight(-n) }}
参考答案
object P19 { def rotate[A](n: Int, ls: List[A]): List[A] = { val nBounded = if (ls.isEmpty) 0 else n % ls.length if (nBounded < 0) rotate(nBounded + ls.length, ls) else (ls drop nBounded) ::: (ls take nBounded) }
0 0
- P19 (**) Rotate a list N places to the left.
- P19 (**) Rotate a list N places to the left.
- VS2010:error C3083: 'Windows': the symbol to the left of a '::' must be a type
- VS2010:error C3083: 'Office': the symbol to the left of a '::' must be a type
- How to add a user to the sudoers list
- Python: how to create a list of n lists [[],[],[]]
- 10 Places to Sell Templates
- ios::ate places the get-position pointer at the file end, enable tellg() to return the size of the f
- MyBatis:The expression 'list' evaluated to a null value
- 转:How to submit the rows of a repeating table in InfoPath to a SharePoint list
- P26 (**) Generate the combinations of K distinct objects chosen from the N elements of a list.
- define a class for a linked list and write a method to delete the nth node.
- How to hidden/display the left panel?
- To The Friends Who Have Left
- a to-do list
- A list to go
- Rotate List
- Rotate List
- [PHP]Mcrypt响应慢的原因解决备注
- PostgreSQL:Java使用CopyManager实现客户端文件COPY导入 .
- 很好String.format使用详解
- android BaseAdapter中改变某个item的部分布局
- 【Android开发经验】我们要友好的告诉用户,程序要崩溃了
- P19 (**) Rotate a list N places to the left.
- 360 so加壳动态脱壳方法
- MySQL 中经验总结
- 花生壳内网版的原理是什么?
- c语言奇数阶魔方阵的实现
- [数据结构]Hash表初学(开放寻址法 )
- OC 中"烦人"的小特性之getter和setter以及property编译指令
- 【Hadoop版】K-Shingle+最小Hash签名+LSH算法+LSH族
- opencv矩阵乘法