Created
February 9, 2024 15:13
-
-
Save kotlinsyntax/d4897128ec7a727c3559f2ed43bbd9ee to your computer and use it in GitHub Desktop.
Simple method to get a random element from a map based on a weight
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
/** | |
* | |
* @param objects: A Map containing the objects to choose from, where the keys represent the objects and the values represent their respective weights. | |
* @return Returns a randomly selected element from a Map, with selection probabilities proportional to each element's weight. | |
* @param <T> A randomly selected element from the Map, or null if the Map is empty. | |
*/ | |
public static <T> T getRandomWeightedElement(Map<T, Number> objects) { | |
double sum = objects.values().stream().mapToDouble(Number::doubleValue).sum(); | |
for (T item : objects.keySet()) { | |
random -= objects.get(item).doubleValue(); | |
if (random <= 0.0d) { | |
return item; | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment