aboutsummaryrefslogtreecommitdiff
path: root/src/common/random.lua
diff options
context:
space:
mode:
authorElias Fleckenstein <eliasfleckenstein@web.de>2020-06-07 18:34:21 +0200
committerElias Fleckenstein <eliasfleckenstein@web.de>2020-06-07 18:34:21 +0200
commit20b8961640b6c22d4149f7268d403cb4609a03fb (patch)
tree0acdb70090ee8db3e77b5a5ad4573cdd13503e8f /src/common/random.lua
parentcc84f066b001f4ea875b115ace6d533d1bc8b4f3 (diff)
downloadskycraft-20b8961640b6c22d4149f7268d403cb4609a03fb.tar.xz
New file Structure
Diffstat (limited to 'src/common/random.lua')
-rw-r--r--src/common/random.lua40
1 files changed, 40 insertions, 0 deletions
diff --git a/src/common/random.lua b/src/common/random.lua
new file mode 100644
index 0000000..4fbbed3
--- /dev/null
+++ b/src/common/random.lua
@@ -0,0 +1,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