Core/src/de/joethei/core/api/utils/RandomCollection.java

41 lines
1.0 KiB
Java

package de.joethei.core.api.utils;
import java.util.NavigableMap;
import java.util.Random;
import java.util.TreeMap;
public class RandomCollection<E>
{
private final NavigableMap<Double, E> map = new TreeMap<Double, E>();
private final Random random;
private double total = 0.0D;
public RandomCollection() {
this(new Random());
}
public RandomCollection(Random random) {
this.random = random;
}
public void add(double weight, E result) {
if (weight <= 0.0D) return;
this.total += weight;
this.map.put(Double.valueOf(this.total), result);
}
public E next() {
double value = this.random.nextDouble() * this.total;
return this.map.ceilingEntry(Double.valueOf(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(Double.valueOf(value)).getValue();
}
}