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

前端 未结 6 2090
南方客
南方客 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 16:04

    Here is my take on the problem:

      def partition[T](items: Seq[T], partitionsCount: Int): List[Seq[T]] = {
        val minPartitionSize = items.size / partitionsCount
        val extraItemsCount = items.size % partitionsCount
    
        def loop(unpartitioned: Seq[T], acc: List[Seq[T]], extra: Int): List[Seq[T]] =
          if (unpartitioned.nonEmpty) {
            val (splitIndex, newExtra) = if (extra > 0) (minPartitionSize + 1, extra - 1) else (minPartitionSize, extra)
            val (newPartition, remaining) = unpartitioned.splitAt(splitIndex)
            loop(remaining, newPartition :: acc, newExtra)
          } else acc
    
        loop(items, List.empty, extraItemsCount).reverse
      }
    

    It's more verbose than some of the other solutions but hopefully more clear as well. reverse is only necessary if you want the order to be preserved.

提交回复
热议问题