P19 (**) Rotate a list N places to the left.

本文介绍了一种使用Scala实现的列表旋转算法,通过两种不同的方法来完成列表元素的旋转操作,并对比了它们的优劣。

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

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值