Last active
July 13, 2022 22:40
-
-
Save gb/670e5440dd828d4bc7ff5d38b8f984b0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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