Skip to content

Instantly share code, notes, and snippets.

@gb
Last active July 13, 2022 22:40
Show Gist options
  • Save gb/670e5440dd828d4bc7ff5d38b8f984b0 to your computer and use it in GitHub Desktop.
Save gb/670e5440dd828d4bc7ff5d38b8f984b0 to your computer and use it in GitHub Desktop.
@Test
public void simpleDistributionTest() {
// Arrange
List<String> data = Arrays.asList("red", "red", "blue", "blue", "green", "green");
// Act
List<String> result = evenlyDistribute(data);
// Assert
List<String> expectation = Arrays.asList("red", "blue", "green", "red", "blue", "green");
assertEquals(expectation, result);
}
private static List<String> evenlyDistribute(List<String> data) {
Map<String, List<String>> partitionedData = data.stream()
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.toList()));
List<String> distributedData = new ArrayList<>();
int currentIndex = 0;
while (distributedData.size() < data.size()) {
for (Map.Entry<String, List<String>> partition : partitionedData.entrySet()) {
if (currentIndex == partition.getValue().size()) {
partitionedData.remove(partition.getKey());
continue;
}
distributedData.add(partition.getValue().get(currentIndex));
}
currentIndex++;
}
return distributedData;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment