Hi so I'm currently working on a system that splits a given Set of UUID's into separate sublists using Guava's Lists.partition method. Here's my code currently:
public static List<List<UUID>> splitPlayers(Set<UUID> players, int numTeams) {
List<UUID> playerList = new ArrayList<>(players);
int partitionSize = players.size() / numTeams;
Collections.shuffle(playerList);
return Lists.partition(playerList, partitionSize);
}
The problem is, this doesn't always work how I want it to.
To be clear, this is how I want it to work:
You provide a Set of UUID's and specify the how many sublists you want the main Set to be split into (numTeams). Based on this, the method should split the Set into exactly the numTeams amount of sublists, and not any more or less sublists then the given numTeams.
The thing is, it doesn't work like that. Here is an example of how it doesn't work properly currently:
I have a feeling that resolving this would require me to perform some extra logic on calculating the partitionSize. The only thing is I'm not sure how to do this.
Any help would be much appreciated. Thanks in advance.
Lists.partition
is working properly - it's just you're not using it properly. You've got a rounding problem, basically: 5 / 2
evaluates to 2, so you're asking for partitions of size 2... so you get 3 partitions. You actually want a partition size of 3, so that you can get all the teams into two partitions. You need to round the partition size up so that numTeams * size >= players.size()
.
The easiest way of doing that is to just add numTeams - 1
before the division:
int partitionSize = (players.size() + numTeams - 1) / numTeams;
See more on this question at Stackoverflow