Partition a collection into “k” close-to-equal pieces (Scala, but language agnostic)

前端 未结 6 2088
南方客
南方客 2021-02-12 15:44

Defined before this block of code:

  • dataset can be a Vector or List
  • numberOfSlices is an Int
6条回答
  •  执念已碎
    2021-02-12 15:58

    If the behavior of xs.grouped(xs.size / n) doesn't work for you, it's pretty easy to define exactly what you want. The quotient is the size of the smaller pieces, and the remainder is the number of the bigger pieces:

    def cut[A](xs: Seq[A], n: Int) = {
      val (quot, rem) = (xs.size / n, xs.size % n)
      val (smaller, bigger) = xs.splitAt(xs.size - rem * (quot + 1))
      smaller.grouped(quot) ++ bigger.grouped(quot + 1)
    }
    

提交回复
热议问题