blob: 4fbbed3a12b6846fc2a906aebbaeabbf0700b4f3 (
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
|
skycraft.random = {
choices = {},
probabilities = {},
csum = {},
sum = 0
}
skycraft.random.__index = skycraft.random
function skycraft.random:new(o)
o = o or {}
setmetatable(o, self)
o.choices = {}
o.probabilities = {}
o.csum = {}
o.sum = 0
return o
end
function skycraft.random:calc_csum()
self.sum = 0
for i, choice in ipairs(self.choices) do
self.sum = self.sum + self.probabilities[choice]
self.csum[choice] = self.sum
end
end
function skycraft.random:choose()
local r = math.random() + math.random(0, self.sum - 1)
for i, choice in pairs(self.choices) do
if r < self.csum[choice] then
return choice
end
end
end
function skycraft.random:add_choice(choice, probability)
table.insert(self.choices, choice)
self.probabilities[choice] = probability
end
|