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

后端 未结 11 1729
盖世英雄少女心
盖世英雄少女心 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:16

    Given:

    val seq = Seq(1,2,3,4,5)
    

    Solution:

    seq.zipWithIndex.groupBy(_._2<3).values.flatMap(_.map(_._1))
    

    or

    seq.zipWithIndex.groupBy(_._2<3).values.flatten.map(_._1)
    

    Result:

    List(4, 5, 1, 2, 3)
    
    1. If rotation is more than length of collection - we need to use rotation%length, if negative than formula (rotation+1)%length and take absolute value.
    2. It's not efficient

提交回复
热议问题