Skip to content

Instantly share code, notes, and snippets.

@MinusKube
Last active November 14, 2019 19:42
Show Gist options
  • Save MinusKube/a4ea909fd165de1b7c0fa44b1527fa0c to your computer and use it in GitHub Desktop.
Save MinusKube/a4ea909fd165de1b7c0fa44b1527fa0c to your computer and use it in GitHub Desktop.
Class for getting random items with given probabilities
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);
}
}
@MinusKube
Copy link
Author

Usage example:

Probabilities<String> probs = new Probabilities<>();
probs.add("Hello", 50);
probs.add("Bonjour", 25);
probs.add("Ciao", 25);

String helloMessage = probs.randomItem();
System.out.println(helloMessage);

/*
    Here, helloMessage has a 50% chance to be "Hello", 25% chance to be "Bonjour" and 25% chance to be "Ciao".
    The total of this example is 100 for better understanding, but it can be any number you want.
*/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment