如何交换到seq中的元素

7ajki6be  于 2021-07-14  发布在  Java
关注(0)|答案(2)|浏览(302)

我有一个练习,我必须交换偶数和奇数位置的元素。例如,从 Seq(1,2,3,4,5) 我得走了 Seq(2,1,4,3,5) .
我想使用slide,然后交换slide seq中的两个元素,但slide将采用如下方式: (1,2) (2,3) (3,4) (4,5) 是吗?有没有函数只取唯一的对?

yvgpqqbh

yvgpqqbh1#

从…开始 grouped() .

mySeq.grouped(2).flatMap{
  case Seq(a,b) => Seq(b,a)
  case x => x
}.toList
9rbhqvlz

9rbhqvlz2#

或者,另一个好的通用方法是模式匹配:

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)

注意,对于尾部递归优化,方法必须声明为final或private(不能重写),并且必须具有线性模式(一个递归案例,任意数量的基本案例)

相关问题