SHARE
TWEET
MathUtils.java
a guest
Oct 12th, 2015
66
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
- public static <T> T weightedRandom(ObjectIntMap<T> objectsWithWeights) {
- int totalWeight = 0;
- for (ObjectIntMap.Entry<T> entry : objectsWithWeights) {
- totalWeight += entry.value;
- }
- int random = MathUtils.random(1, totalWeight);
- int weightCovered = 0;
- for (ObjectIntMap.Entry<T> entry : objectsWithWeights) {
- weightCovered += entry.value;
- if (random <= weightCovered) {
- return entry.key;
- }
- }
- throw new GdxRuntimeException("Could not determine a random object by the given weights.");
- }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

