Reputation: 139
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?
Upvotes: 4
Views: 260
Reputation: 724
Alternatively, another good generic approach is pattern matching:
val testList: List[Int] = List(1, 2, 3, 4, 5)
def swapEvenAndOddElementsRecursively( listToSwap: List[Int]): List[Int] = {
listToSwap match {
// Base Cases (2) Empty list and list with single element
case Nil | _ :: Nil => listToSwap
// Recursive case take 2 elements swap and process rest of list
case firstElement :: secondElement :: rest => secondElement :: firstElement :: swapEvenAndOddElementsRecursively(rest)
}
}
@tailrec
final def swapEvenAndOddElementsWithTailRecursion( listToSwap: List[Int], result: List[Int] = List.empty): List[Int] = {
listToSwap match {
// Base Case (1) Empty list
case Nil => result
// Base Case (2) List with single element
case singleNumber :: Nil => result ::: List(singleNumber)
// Recursive case take 2 elements swap, append to result, and process rest of list
case firstElement :: secondElement :: rest =>
val updatedResult: List[Int] = result ::: List(secondElement, firstElement)
// val updatedResult: List[Int] = (firstElement :: secondElement :: result.reverse).reverse
swapEvenAndOddElementsWithTailRecursion(rest, updatedResult)
}
}
println(swapEvenAndOddElementsRecursively(testList))
// List(2, 1, 4, 3, 5)
println(swapEvenAndOddElementsWithTailRecursion(testList))
// List(2, 1, 4, 3, 5)
Note that for the tail recursive optimization, the method must be declared as either final or private (it cannot be overridden) and it must have linear pattern (one recursive case, arbitrary number of base cases)
Upvotes: 0
Reputation: 51271
Start with grouped()
.
mySeq.grouped(2).flatMap{
case Seq(a,b) => Seq(b,a)
case x => x
}.toList
Upvotes: 5