Skip to content

Instantly share code, notes, and snippets.

@kotlinsyntax
Created February 9, 2024 15:13
Show Gist options
  • Save kotlinsyntax/d4897128ec7a727c3559f2ed43bbd9ee to your computer and use it in GitHub Desktop.
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
/**
*
* @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