How to group a variable-length, repeating sequence in Scala

后端 未结 4 1556
生来不讨喜
生来不讨喜 2020-12-31 22:14

I have a collection of ints that repeat themselves in a pattern:

val repeatingSequence = List(1,2,3,1,2,3,4,1,2,1,2,3,4,5)

I\'d like to sec

4条回答
  •  一生所求
    2020-12-31 22:58

    import scala.collection.mutable.ListBuffer
    import scala.collection.breakOut
    
    val repeatingSequence = List(1,2,3,1,2,3,4,1,2,1,2,3,4,5)
    val groupedBySequence: List[List[Int]] = repeatingSequence.foldLeft(ListBuffer[ListBuffer[Int]]()) {
      case (acc, 1) => acc += ListBuffer(1)
      case (acc, n) => acc.last += n; acc
    }.map(_.toList)(breakOut)
    

提交回复
热议问题