Last active
November 14, 2019 19:42
-
-
Save MinusKube/a4ea909fd165de1b7c0fa44b1527fa0c to your computer and use it in GitHub Desktop.
Class for getting random items with given probabilities
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
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.Random; | |
public class Probabilities<T> { | |
private static Random random = new Random(); | |
private Map<T, Float> items; | |
public Probabilities() { | |
items = new HashMap<>(); | |
} | |
public void add(T item, float prob) { items.put(item, prob); } | |
public void remove(T item) { items.remove(item); } | |
public Map<T, Float> getItems() { return new HashMap<>(items); } | |
public T randomItem() { | |
float total = 0; | |
for (float proba : items.values()) { | |
total += proba; | |
} | |
float randomNum = random.nextFloat(); | |
randomNum *= total; | |
float cur = 0; | |
for(T item : items.keySet()) { | |
float proba = items.get(item); | |
if(randomNum >= cur && randomNum < cur + proba) { | |
return item; | |
} | |
cur += proba; | |
} | |
return items.keySet().stream().findFirst().orElse(null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example: