Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to partition a list into groups

I have a list of names.

I want to partition this list into groups of a specified size. All groups should be equal to or less than the specified size, with an equal as possible group size across the groups, and as close to the specified size as possible.

What algorithm (Java-esque pseudo code if possible please!) determines the most appropriate group sizes?

For example:

List contains 13 names - max team size 3. Output (group sizes): 3, 3, 3, 2, 2

List contains 13 names - max team size 4. Output: 4, 3, 3, 3

List contains 31 names - max team size 5. Output: 5, 5, 5, 4, 4, 4, 4

List contains 31 names - max team size 6. Output: 6, 5, 5, 5, 5, 5

List contains 31 names - max team size 10. Output: 8, 8, 8, 7

like image 255
Keith Avatar asked Feb 22 '23 20:02

Keith


2 Answers

It's pretty straightforward. You calculate the result of N div M and add 1 to have the correct number of arrays (N is the list length and M the max team size), then you iterate on all arrays to add an item until you run out of items

example : 43 names, max team number 4 => 43 mod 4 + 1 = 11, remains 3. so 11 arrays (10 with 4 and 1 with 3)

like image 103
Grooveek Avatar answered Feb 24 '23 10:02

Grooveek


I'm not going to write code for this, but

  1. If the list size is a multiple of the max team size, divide by team size to get the number of groups, all of max size, and stop.
  2. Integer-divide the list size by the max team size, then add one. That's the number of groups.
  3. Subtract the list size from that next higher multiple; that's the number of teams that are one less than the max size.

This obviously only works for inputs that are close to working out; it fails if the max team size is large compared to the size of the list.

like image 25
Ernest Friedman-Hill Avatar answered Feb 24 '23 09:02

Ernest Friedman-Hill