Advertisement
Guest User

Random objects

a guest
May 17th, 2014
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. import java.util.Random;
  2. import java.util.HashMap;
  3. import java.util.function.Supplier;
  4.  
  5. class A {}
  6. class B {}
  7. class C {}
  8. class D {}
  9.  
  10. class RandomGenerator {
  11.     private final Supplier[] numbers, generators;
  12.     private final Random rand = new Random();
  13.    
  14.     RandomGenerator(Supplier[] probabilities) {
  15.         int len = probabilities.length/2;
  16.         numbers = new Supplier[len];
  17.         generators = new Supplier[len];
  18.         for(int i = 0; i < len; i++) {
  19.             numbers[i]    = probabilities[i*2];
  20.             generators[i] = probabilities[i*2+1];
  21.         }
  22.     }
  23.    
  24.     private double toDouble(Object o) {
  25.         if(o instanceof Integer) return (Integer)o;
  26.         else return (Double)o;
  27.     }
  28.    
  29.     Object next() {
  30.         double total = 0;
  31.         double[] totals = new double[numbers.length];
  32.         for(int i = 0; i < numbers.length; i++) {
  33.             total += toDouble(numbers[i].get());
  34.             totals[i] = total;
  35.         }
  36.         double rnd = rand.nextDouble() * total;
  37.         int index = 0;
  38.         while(totals[index] < rnd) index++;
  39.         return generators[index].get();
  40.     }
  41. }
  42. public class RandomTest {
  43.     public static void main(String[] args) {
  44.         Supplier[] probabilities = {
  45.             () -> 50, () -> new A(),
  46.             () -> 10, () -> new B(),
  47.             () -> 35, () -> new C(),
  48.             () ->  5, () -> new D()
  49.         };
  50.         RandomGenerator rg = new RandomGenerator(probabilities);
  51.         HashMap<Class, Integer> map = new HashMap<>();
  52.        
  53.         for(int i = 0; i < 100000; i++) {
  54.             Object o = rg.next();
  55.             map.merge(o.getClass(), 1, (oldNum, x) -> oldNum + 1);
  56.         }
  57.        
  58.         System.out.println(map);
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement