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

前端 未结 6 2089
南方客
南方客 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:01

    I'd approach it this way: Given n elements and m partitions (n>m), either n mod m == 0 in which case, each partition will have n/m elements, or n mod m = y, in which case you'll have each partition with n/m elements and you have to distribute y over some m.

    You'll have y slots with n/m+1 elements and (m-y) slots with n/m. How you distribute them is your choice.

提交回复
热议问题