Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap to elements in Seq

I have an exercise where I have to swap elements on even and odd positions. For example, from Seq(1,2,3,4,5) I have to get Seq(2,1,4,3,5).

I wanted to use sliding and then swap two elements in the slid Seq, but sliding will take something like this: (1,2) (2,3) (3,4) (4,5), won't it? Is there any function to take only unique pairs?

like image 636
squall Avatar asked Sep 19 '25 10:09

squall


1 Answers

Start with grouped().

mySeq.grouped(2).flatMap{
  case Seq(a,b) => Seq(b,a)
  case x => x
}.toList
like image 190
jwvh Avatar answered Sep 22 '25 06:09

jwvh