How do you rotate (circular shift) of a Scala collection

后端 未结 11 1670
盖世英雄少女心
盖世英雄少女心 2020-12-19 03:40

I can do this quite easily, and cleanly, using a for loop. For instance, if I wanted to traverse a Seq from every element back to itself I would do the

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-19 04:21

    Here is one liner solution

    def rotateRight(A: Array[Int], K: Int): Array[Int] = {
        if (null == A || A.size == 0) A else (A drop A.size - (K % A.size)) ++ (A take A.size - (K % A.size))
    }
    rotateRight(Array(1,2,3,4,5), 3)
    

提交回复
热议问题