SHARE
TWEET

MathUtils.java

a guest Oct 12th, 2015 66 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.     public static <T> T weightedRandom(ObjectIntMap<T> objectsWithWeights) {
  2.         int totalWeight = 0;
  3.         for (ObjectIntMap.Entry<T> entry : objectsWithWeights) {
  4.             totalWeight += entry.value;
  5.         }
  6.  
  7.         int random = MathUtils.random(1, totalWeight);
  8.  
  9.         int weightCovered = 0;
  10.         for (ObjectIntMap.Entry<T> entry : objectsWithWeights) {
  11.             weightCovered += entry.value;
  12.             if (random <= weightCovered) {
  13.                 return entry.key;
  14.             }
  15.         }
  16.  
  17.         throw new GdxRuntimeException("Could not determine a random object by the given weights.");
  18.     }
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. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top