summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java
blob: bf3b4b6d8dabacc893424f1e8b460d1ba6ed2cf2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package bjc.utils.gen;

import java.util.Random;
import bjc.utils.funcdata.FunctionalList;
import bjc.utils.data.GenHolder;
import bjc.utils.data.IHolder;
import bjc.utils.data.Pair;

/**
 * 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> {
	/**
	 * The list of probabilities for each result
	 */
	private FunctionalList<Integer>	probs;

	/**
	 * The list of possible results to pick from
	 */
	private FunctionalList<E>		results;

	/**
	 * The source for any needed random numbers
	 */
	private Random					src;

	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));
		IHolder<E> res = new GenHolder<E>();
		GenHolder<Boolean> bl = new GenHolder<>(true);

		probs.forEachIndexed((i, p) -> {
			if (bl.unwrap(vl -> vl)) {
				if (v.unwrap((vl) -> vl < p)) {
					res.transform((vl) -> results.getByIndex(i));

					bl.transform((vl) -> false);
				} else {
					v.transform((vl) -> vl - p);
				}
			}
		});

		return res.unwrap((vl) -> vl);
	}

	/**
	 * Return a list of values that can be generated by this generator
	 * 
	 * @return A list of all the values that can be generated
	 */
	public FunctionalList<E> getResults() {
		return results;
	}

	/**
	 * Return a list containing values that can be generated paired with
	 * the probability of those values being generated
	 * 
	 * @return A list of pairs of values and value probabilities
	 */
	public FunctionalList<Pair<Integer, E>> getValues() {
		return probs.pairWith(results);
	}
}