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)
//19 def 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)
}
本文介绍了一种使用Scala实现的列表旋转算法,通过两种不同的方法来完成列表元素的旋转操作,并对比了它们的优劣。
897

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



