Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- import java.util.HashMap;
- import java.util.function.Supplier;
- class A {}
- class B {}
- class C {}
- class D {}
- class RandomGenerator {
- private final Supplier[] numbers, generators;
- private final Random rand = new Random();
- RandomGenerator(Supplier[] probabilities) {
- int len = probabilities.length/2;
- numbers = new Supplier[len];
- generators = new Supplier[len];
- for(int i = 0; i < len; i++) {
- numbers[i] = probabilities[i*2];
- generators[i] = probabilities[i*2+1];
- }
- }
- private double toDouble(Object o) {
- if(o instanceof Integer) return (Integer)o;
- else return (Double)o;
- }
- Object next() {
- double total = 0;
- double[] totals = new double[numbers.length];
- for(int i = 0; i < numbers.length; i++) {
- total += toDouble(numbers[i].get());
- totals[i] = total;
- }
- double rnd = rand.nextDouble() * total;
- int index = 0;
- while(totals[index] < rnd) index++;
- return generators[index].get();
- }
- }
- public class RandomTest {
- public static void main(String[] args) {
- Supplier[] probabilities = {
- () -> 50, () -> new A(),
- () -> 10, () -> new B(),
- () -> 35, () -> new C(),
- () -> 5, () -> new D()
- };
- RandomGenerator rg = new RandomGenerator(probabilities);
- HashMap<Class, Integer> map = new HashMap<>();
- for(int i = 0; i < 100000; i++) {
- Object o = rg.next();
- map.merge(o.getClass(), 1, (oldNum, x) -> oldNum + 1);
- }
- System.out.println(map);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement