-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeightedRandomSelector.cs
More file actions
72 lines (61 loc) · 1.49 KB
/
WeightedRandomSelector.cs
File metadata and controls
72 lines (61 loc) · 1.49 KB
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
using UnityEngine;
using System.Collections;
namespace Uzu
{
/// <summary>
/// Allows weighted-random selection of a list of objects.
/// </summary>
public class WeightedRandomSelector
{
private float[] _weights;
private float _totalWeight;
public WeightedRandomSelector ()
{
}
public WeightedRandomSelector (float[] weights)
{
Reinitialize (weights);
}
/// <summary>
/// Reinitialize the specified weights for this selector.
/// This allows the selector object to be re-used without
/// having to re-allocate a new one.
/// </summary>
public void Reinitialize (float[] weights)
{
_weights = weights;
_totalWeight = 0.0f;
// Calculate total weight.
{
for (int i = 0; i < _weights.Length; i++) {
_totalWeight += _weights [i];
}
}
}
/// <summary>
/// Selected an item using weighted random calculation
/// and return its index.
/// </summary>
public int SelectIndex ()
{
// All weights are zero.
if (Mathf.Approximately(_totalWeight, 0.0f)) {
return _weights.Length;
}
float rnd = Random.value * _totalWeight;
// Since Unity RNG sometimes generates 1.0f, we need to handle this case.
if (Mathf.Approximately (rnd, _totalWeight)) {
rnd *= 0.5f;
}
for (int i = 0; i < _weights.Length; i++) {
rnd -= _weights [i];
if (rnd < 0.0f) {
return i;
}
}
// Should never get here.
Debug.LogWarning ("Unable to calculate weighted random.");
return _weights.Length;
}
}
}