-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandom_weight_picker.nut
92 lines (85 loc) · 1.87 KB
/
random_weight_picker.nut
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
local _ctx = this;
class WeightItem
{
weight = null;
weightPos = null;
name = null;
constructor(name, weight, weightPos)
{
this.name = name;
this.weight = weight;
this.weightPos = weightPos;
}
function InRange(pos)
{
if (pos < weightPos)
{
return -1;
}
if (pos > weightPos + weight)
{
return 1;
}
return 0;
}
}
class RandomWeightPicker
{
_weightItems = null;
_totalWeight = null;
constructor(weightTable)
{
_weightItems = [];
local currentPos = 0.0;
foreach (name, weight in weightTable)
{
weight = weight.tofloat();
local item = _ctx.WeightItem(name, weight, currentPos);
currentPos += weight;
_weightItems.append(item);
}
_totalWeight = currentPos;
}
//return name : string
function Pick()
{
local pos = RandomFloat(0.0, _totalWeight);
local left = 0;
local right = _weightItems.len() - 1;
if (_weightItems[left].InRange(pos) == 0)
{
return _weightItems[left].name;
}
if (_weightItems[right].InRange(pos) == 0)
{
return _weightItems[right].name;
}
while (true)
{
if (left == right)
{
return _weightItems[left].name;
}
local mid = (left + right) / 2;
local r = _weightItems[mid].InRange(pos);
if (r < 0)
{
right = mid;
}
else if (r > 0)
{
left = mid;
}
else
{
return _weightItems[mid].name;
}
}
}
}
function GetPublicMemberNames()
{
return [
"RandomWeightPicker"
];
}