Skip to content

Instantly share code, notes, and snippets.

@NahuLD
Last active August 28, 2019 16:21
Show Gist options
  • Save NahuLD/3503765c7bda8f2e418724a6def60570 to your computer and use it in GitHub Desktop.
Save NahuLD/3503765c7bda8f2e418724a6def60570 to your computer and use it in GitHub Desktop.
Simple class to get random items from a collection. Recommended for chances.
package $package;
import java.util.TreeMap;
import java.util.NavigableMap;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public final class RandomCollection<E> {
private final NavigableMap<Double, E> map = new TreeMap<>();
private final Random random;
private double total = 0;
public RandomCollection() {
this(ThreadLocalRandom.current());
}
public RandomCollection(Random random) {
this.random = random;
}
public void add(double weight, E result) {
if (weight <= 0) return;
total += weight;
map.put(total, result);
}
public E next() {
double value = random.nextDouble() * total;
return map.higherEntry(value).getValue();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment