Draco18s

WeightedRanomExample

Jun 29th, 2017
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.86 KB | None | 0 0
  1. SomeClass {
  2.     public class WeightedItem {
  3.         public readonly int weight;
  4.         public readonly Item drop;
  5.         public WeightedItem(Item i, int w) {
  6.             drop = i;
  7.             weight = w;
  8.         }
  9.        
  10.         public ItemStack GetStackFromDrop() {
  11.             return new ItemStack(drop);
  12.         }
  13.     }
  14.  
  15.     private List<WeightedItem> bucket = new List<WeightedItem>();
  16.     private totalWeight = 0;
  17.    
  18.     public void Add (Item item, int count) {
  19.         if(count <= 0) throw new Exception("Invalid random weight");
  20.         bucket.Add(new WeightedItem(item, count));
  21.         totalWeight += count;
  22.     }
  23.    
  24.     public void Add(WeightedItem item) {
  25.         bucket.Add(item);
  26.         totalWeight += item.weight;
  27.     }
  28.  
  29.     public ItemStack GetRandom (Random rng) {
  30.         int randomVal = rng.Next(0, totalWeight);
  31.         foreach(WeightedItem item in bucket) {
  32.             randomVal -= item.weight;
  33.             if(randomVal <= 0) {
  34.                 return item.GetStackFromDrop();
  35.             }
  36.         }
  37.     }
  38. }
Add Comment
Please, Sign In to add comment