我可以使用for循环非常轻松地干净利落地完成这项任务。例如,如果我想从每个元素遍历Seq
回到自身,我会执行以下操作:
val seq = Seq(1,2,3,4,5)
for (i <- seq.indices) {
for (j <- seq.indices) {
print(seq(i + j % seq.length))
}
}
但是我正在寻找fold
收藏品,我想知道是否有更惯用的方法。递归方法可以让我避免任何var
。但基本上,我想知道以下是否可能:
seq.rotatedView(i)
这将创建旋转视图,如旋转位(或循环移位)。
答案 0 :(得分:16)
如下所示:
scala> def rotatedView(i:Int)=Seq(1,2,3,4,5).drop(i)++Seq(1,2,3,4,5).take(i)
rotatedView: (i: Int)Seq[Int]
scala> rotatedView(1)
res48: Seq[Int] = List(2, 3, 4, 5, 1)
scala> rotatedView(2)
res49: Seq[Int] = List(3, 4, 5, 1, 2)
答案 1 :(得分:6)
这应该以相当通用的方式进行,并允许任意轮换:
def rotateLeft[A](seq: Seq[A], i: Int): Seq[A] = {
val size = seq.size
seq.drop(i % size) ++ seq.take(i % size)
}
def rotateRight[A](seq: Seq[A], i: Int): Seq[A] = {
val size = seq.size
seq.drop(size - (i % size)) ++ seq.take(size - (i % size))
}
这个想法很简单,向左旋转,drop
左边的第一个i
元素,再从左边再take
个,以相反的顺序连接它们。如果您不介意计算集合的大小,则可以以大小为模的操作,以允许i
任意。
scala> rotateRight(seq, 1)
res34: Seq[Int] = List(5, 1, 2, 3, 4)
scala> rotateRight(seq, 7)
res35: Seq[Int] = List(4, 5, 1, 2, 3)
scala> rotateRight(seq, 70)
res36: Seq[Int] = List(1, 2, 3, 4, 5)
同样,您可以使用splitAt
:
def rotateLeft[A](seq: Seq[A], i: Int): Seq[A] = {
val size = seq.size
val (first, last) = seq.splitAt(i % size)
last ++ first
}
def rotateRight[A](seq: Seq[A], i: Int): Seq[A] = {
val size = seq.size
val (first, last) = seq.splitAt(size - (i % size))
last ++ first
}
使用增强我的库模式使其更加通用:
import scala.collection.TraversableLike
import scala.collection.generic.CanBuildFrom
implicit class TraversableExt[A, Repr <: TraversableLike[A, Repr]](xs: TraversableLike[A, Repr]) {
def rotateLeft(i: Int)(implicit cbf: CanBuildFrom[Repr, A, Repr]): Repr = {
val size = xs.size
val (first, last) = xs.splitAt(i % size)
last ++ first
}
def rotateRight(i: Int)(implicit cbf: CanBuildFrom[Repr, A, Repr]): Repr = {
val size = xs.size
val (first, last) = xs.splitAt(size - (i % size))
last ++ first
}
}
scala> Seq(1, 2, 3, 4, 5).rotateRight(2)
res0: Seq[Int] = List(4, 5, 1, 2, 3)
scala> List(1, 2, 3, 4, 5).rotateLeft(2)
res1: List[Int] = List(3, 4, 5, 1, 2)
scala> Stream(1, 2, 3, 4, 5).rotateRight(1)
res2: scala.collection.immutable.Stream[Int] = Stream(5, ?)
请记住,这些并非一定都是性能最佳的,并且它们也无法使用无限集合(没有人可以)。
答案 2 :(得分:5)
根据OP的意见,他们想要折叠它,这里略有不同,避免先计算序列的长度。
定义迭代器,迭代旋转的序列
class RotatedIterator[A](seq: Seq[A], start: Int) extends Iterator[A] {
var (before, after) = seq.splitAt(start)
def next = after match {
case Seq() =>
val (h :: t) = before; before = t; h
case h :: t => after = t; h
}
def hasNext = after.nonEmpty || before.nonEmpty
}
并像这样使用它:
val seq = List(1, 2, 3, 4, 5)
val xs = new RotatedIterator(seq, 2)
println(xs.toList) //> List(3, 4, 5, 1, 2)
答案 3 :(得分:3)
一种简单的方法是将序列与其自身连接起来,然后采用所需的slice
:
(seq ++ seq).slice(start, start + seq.length)
这只是drop
/ take
版本的变体,但也许更清晰一些。
答案 4 :(得分:2)
鉴于:
val seq = Seq(1,2,3,4,5)
解决方案:
seq.zipWithIndex.groupBy(_._2<3).values.flatMap(_.map(_._1))
或
seq.zipWithIndex.groupBy(_._2<3).values.flatten.map(_._1)
结果:
List(4, 5, 1, 2, 3)
rotation%length
,如果为负,则使用公式(rotation+1)%length
并取绝对值。答案 5 :(得分:0)
这是一个班轮解决方案
def rotateRight(A: Array[Int], K: Int): Array[Int] = {
if (null == A || A.size == 0) A else (A drop A.size - (K % A.size)) ++ (A take A.size - (K % A.size))
}
rotateRight(Array(1,2,3,4,5), 3)
答案 6 :(得分:0)
这是一种相当简单且惯用的Scala集合编写方式:
def rotateSeq[A](seq: Seq[A], isLeft: Boolean = false, count: Int = 1): Seq[A] =
if (isLeft)
seq.drop(count) ++ seq.take(count)
else
seq.takeRight(count) ++ seq.dropRight(count)
答案 7 :(得分:0)
我们可以简单地使用foldLeft
来反转列表,如下所示。
val input = List(1,2,3,4,5)
val res = input.foldLeft(List[Int]())((s, a) => { List(a) ++: s})
println(res) // List(5, 4, 3, 2, 1)
答案 8 :(得分:0)
另一种尾递归方法。当我使用JMH进行基准测试时,它比基于放置/获取的解决方案快大约2倍:
def rotate[A](list: List[A], by: Int): List[A] = {
@tailrec
def go(list: List[A], n: Int, acc: List[A]): List[A] = {
if(n > 0) {
list match {
case x :: xs => go(xs, n-1, x :: acc)
}
} else {
list ++ acc.reverse
}
}
if (by < 0) {
go(list, -by % list.length, Nil)
} else {
go(list, list.length - by % list.length, Nil)
}
}
//rotate right
rotate(List(1,2,3,4,5,6,7,8,9,10), 3) // List(8, 9, 10, 1, 2, 3, 4, 5, 6, 7)
//use negative number to rotate left
rotate(List(1,2,3,4,5,6,7,8,9,10), -3) // List(4, 5, 6, 7, 8, 9, 10, 1, 2, 3)
答案 9 :(得分:0)
这是一段简单的代码
object tesing_it extends App
{
val one = ArrayBuffer(1,2,3,4,5,6)
val i = 2 //the number of index you want to move
for(z<-0 to i){
val y = 0
var x = one += one(y)
x = x -= x(y)
println("for seq after process " +z +" " + x)
}
println(one)
}
结果:
对于进程0 ArrayBuffer(2、3、4、5、6、1)之后的seq
对于进程1 ArrayBuffer(3,4,5,6,1,1,2)之后的seq
对于进程2 ArrayBuffer(4,5,6,1,2,3)之后的seq
ArrayBuffer(4,5,6,1,2,3)
答案 10 :(得分:0)
如果您不需要验证“偏移量”,则可以使用另一种解决方案:
def rotate[T](seq: Seq[T], offset: Int): Seq[T] = Seq(seq, seq).flatten.slice(offset, offset + seq.size)