Last active
August 28, 2019 16:21
-
-
Save NahuLD/3503765c7bda8f2e418724a6def60570 to your computer and use it in GitHub Desktop.
Simple class to get random items from a collection. Recommended for chances.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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