acegiak

Weighted Random Algorithms

May 28th, 2013
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.93 KB | None | 0 0
  1. Weighted Random 1:
  2. (Requires you know the sum of all the weights)
  3. Expensiveness: 2n+r;
  4.  
  5. function Object WeightedRandom(ArrayList<Object> objects){
  6.     float sum = getWeightSums(objects);
  7.     float selected = (new Random()).nextFloat() * sum;
  8.     float upTo = 0f;
  9.     for(Object object : objects){
  10.         if(selected < upto + object.weight){
  11.             return object;
  12.         }
  13.     }
  14. }
  15.  
  16.  
  17.  
  18. Weighted Random 2:
  19. (Requires all the weights are between 0 and 1)
  20. Expensiveness: n*r;
  21.  
  22.  
  23. function Object WeightedRandom(ArrayList<Object> objects){
  24.     for(Object object : objects){
  25.         if((new Random()).nextFloat() <  object.weight){
  26.             return object;
  27.         }
  28.     }
  29. }
  30.  
  31. Weighted Random 3:
  32. (Assumes you know the Max of all the weights)
  33. Expensiveness: n+n*r
  34.  
  35. function Object WeightedRandom(ArrayList<Object> objects){
  36.     float max = getWeightMax(objects);
  37.     for(Object object : objects){
  38.         if((new Random()).nextFloat()*max < object.weight){
  39.             return object;
  40.         }
  41.     }
  42. }
Add Comment
Please, Sign In to add comment