Core/src/main/java/eu/univento/core/api/utils/RandomCollection.java

45 lines
1.0 KiB
Java

/*
* Copyright (c) 2017 univento.eu - All rights reserved
* You are not allowed to use, distribute or modify this code
*/
package eu.univento.core.api.utils;
import java.util.NavigableMap;
import java.util.Random;
import java.util.TreeMap;
class RandomCollection<E> {
private final NavigableMap<Double, E> map = new TreeMap<>();
private final Random random;
private double total = 0.0D;
public RandomCollection() {
this(new Random());
}
private RandomCollection(Random random) {
this.random = random;
}
public void add(double weight, E result) {
if (weight <= 0.0D) return;
this.total += weight;
this.map.put(this.total, result);
}
public E next() {
double value = this.random.nextDouble() * this.total;
return this.map.ceilingEntry(value).getValue();
}
public E random() {
double value = this.random.nextDouble() * this.total;
while (this.random.nextBoolean()) {
value = this.random.nextDouble() * this.total;
}
return this.map.ceilingEntry(value).getValue();
}
}