Skip to content

Instantly share code, notes, and snippets.

@gabrielbs21
Created May 4, 2021 15:37
Show Gist options
  • Save gabrielbs21/f3e3620b7e85d1eee205fb5ecb680e75 to your computer and use it in GitHub Desktop.
Save gabrielbs21/f3e3620b7e85d1eee205fb5ecb680e75 to your computer and use it in GitHub Desktop.
Create a data collection to randomly pick it up.
import java.util.NavigableMap;
import java.util.Random;
import java.util.TreeMap;
public class RandomCollection<E> {
private final NavigableMap<Double, E> map = new TreeMap<>();
private final Random random;
private double total = 0;
public RandomCollection() {
this(new Random());
}
public RandomCollection(Random random) {
this.random = random;
}
public void add(double chance, E result) {
if (chance <= 0) return;
total += chance;
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