Mahek Shah
Mahek Shah

Reputation: 495

How to repeatedly swap elements in scala list?

I have a List

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

I want to consecutive swap the elements How can I do this?

Expected ans is

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

Upvotes: 4

Views: 1019

Answers (4)

elm
elm

Reputation: 20405

A recursive function for repeated swaps, as follows,

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

Note that

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

f(f(a)) == a
true

Upvotes: 1

curious
curious

Reputation: 2928

Sliding can also be used :

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)

Or

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

Upvotes: 5

Binzi Cao
Binzi Cao

Reputation: 1085

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)

Upvotes: 17

Rahul
Rahul

Reputation: 893

The key is to use grouped while working on groups:

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)

Upvotes: 6

Related Questions