假设我有一张桌子,比如:
skins = {desert_camouflage = 10, forest_camouflage = 20}其中"desert_camouflage“比"forest_camouflage”加权得少。
我正在搜索一个Rbx.Lua RNG函数,它将打印它的结果。
发布于 2014-11-11 00:06:40
我不这么认为,但你自己写起来很容易:
function(weights)
local sum = 0
for _, v in next, weights do
if v < 0 or math.floor(v) ~= v then
error "Weights must be non-negative integers"
end
sum = sum + v
end
sum = math.random(sum)
for k, v in next, weights do
sum = sum - v
if sum <= 0 then
return k
end
end
error "Should not happen."
end发布于 2021-06-07 19:17:53
试试我的解决方案:
function weighted_random (weights)
local summ = 0
for i, weight in pairs (weights) do
summ = summ + weight
end
if summ == 0 then return end
-- local value = math.random (summ) -- for integer weights only
local value = summ*math.random ()
summ = 0
for i, weight in pairs (weights) do
summ = summ + weight
if value <= summ then
return i, weight
end
end
endhttps://stackoverflow.com/questions/26855156
复制相似问题