diff options
| author | bculkin2442 <bjculkin@mix.wvu.edu> | 2015-09-29 13:35:50 -0400 |
|---|---|---|
| committer | bculkin2442 <bjculkin@mix.wvu.edu> | 2015-09-29 13:35:50 -0400 |
| commit | 4e4d470626087c26ee18f5cb04c86647b5f2699c (patch) | |
| tree | 869a5c7452c50b1e751d86e7058d090f3d55f69b /BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java | |
| parent | 47577a40bc0e298041ab0915fa4bdc3355d53349 (diff) | |
Added random grammar support.
Import of library code from version 1 finished. Now for more library
code and examples on library usage.
Diffstat (limited to 'BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java')
| -rw-r--r-- | BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java new file mode 100644 index 0000000..ecd4e36 --- /dev/null +++ b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java @@ -0,0 +1,68 @@ +package bjc.utils.gen; + +import java.util.Random; + +import bjc.utils.funcdata.FunctionalList; +import bjc.utils.data.GenHolder; + +/** + * Represents a random number generator where certain results are weighted more heavily than + * others. + * @author ben + * + * @param <E> The type of values that are randomly selected. + */ +public class WeightedRandom<E> { + private Random src; + + private FunctionalList<Integer> probs; + private FunctionalList<E> results; + + private int totalChance; + + /** + * Create a new weighted random generator with the specified source of randomness + * @param sr The source of randomness to use. + */ + public WeightedRandom(Random sr) { + probs = new FunctionalList<>(); + results = new FunctionalList<>(); + + src = sr; + } + + /** + * Add a probability for a specific result to be given. + * @param chance The chance to get this result. + * @param res The result to get when the chance comes up. + */ + public void addProb(int chance, E res) { + probs.add(chance); + results.add(res); + + totalChance += chance; + } + + /** + * Generate a weighted random value. + * @return A random value selected in a weighted fashion. + */ + public E genVal() { + GenHolder<Integer> v = new GenHolder<>(src.nextInt(totalChance)); + GenHolder<E> res = new GenHolder<E>(); + GenHolder<Boolean> bl = new GenHolder<>(true); + + probs.forEachIndexed((i, p) -> { + if (bl.held) { + if (v.held < p) { + res.held = results.getByIndex(i); + bl.held = false; + } else { + v.held -= p; + } + } + }); + + return res.held; + } +} |
