Created
May 4, 2021 15:37
-
-
Save gabrielbs21/f3e3620b7e85d1eee205fb5ecb680e75 to your computer and use it in GitHub Desktop.
Create a data collection to randomly pick it up.
This file contains 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
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