lua实现:
按照tableTest
里的设置概率返回结果
local tableTest = {
a = 0.3,
b = 0.2,
c = 0.4,
d = 0.1
}
-- 构造用于计数的Table
local tableCount = {}
-- 构造概率总和变量
local totalProb = 0
-- 计算概率总和
for k, v in pairs(tableTest) do
totalProb = totalProb + v
tableCount[k] = totalProb
end
-- 返回随机结果
local function getResult()
local randomNum = math.random() * totalProb
for k, v in pairs(tableCount) do
if randomNum <= v then
return k
end
end
end
return getResult()
单纯来赚个金币(bushi)
来自QQ: "简律纯"和"krypton"的聊天记录如下:
———————— 2023-01-06 ————————
简律纯 14:31:44
for i=1,10 do
msg:echo(getResult())
end
krypton 14:31:46
c
krypton 14:31:46
a
krypton 14:31:46
b
krypton 14:31:46
c
krypton 14:31:46
c
krypton 14:31:46
c
krypton 14:31:47
c
krypton 14:31:47
a
krypton 14:31:47
a
krypton 14:31:48
b