如何在scala列表中重复交换元素?

时间:2015-09-22 05:25:02

标签: scala

我有一个列表

val a= List(1,2,3,4,5,6,7)

我想连续交换元素我该怎么做?

预期的是

List(2,1,4,3,6,5,7)

4 个答案:

答案 0 :(得分:18)

scala> List(1,2,3,4,5,6,7).grouped(2).flatMap(_.reverse).toList
res10: List[Int] = List(2, 1, 4, 3, 6, 5, 7)

答案 1 :(得分:7)

关键是在处理群组时使用分组:

val a= List(1,2,3,4,5,6,7)
a.grouped(2).flatMap{_.reverse}.toList
//res0: List[Int] = List(2, 1, 4, 3, 6, 5, 7)

答案 2 :(得分:5)

也可以使用滑动:

scala> List(1,2,3,4,5,6).sliding(2,2).foldLeft(List[Int]()){(r,c) => r :+ c.last :+ c.head }.toList
res0: List[Int] = List(2, 1, 4, 3, 6, 5)

或者

scala> List(1,2,3,4,5,6).sliding(2,2).flatMap(_.reverse).toList
res1: List[Int] = List(2, 1, 4, 3, 6, 5)

答案 3 :(得分:1)

重复交换的递归函数,如下所示,

def f(xs: List[Int]): List[Int] = {
  xs match {
    case Nil => Nil
    case x :: Nil => List(x)
    case x :: y :: ys => y :: x :: f(ys)
  }
}

请注意

f(a)
List(2, 1, 4, 3, 6, 5, 7)

f(f(a)) == a
true