如何在ROBLOX Lua中制作加权随机数生成器?(类似于CS:GO箱子)

假设我有一个表格如下:

skins = {desert_camouflage = 10, forest_camouflage = 20}

其中“desert_camouflage”比“forest_camouflage”更加稀有。

我正在寻找一个可以打印结果的Rbx.Lua RNG函数。

点赞
用户3204551
用户3204551

我不这么认为,但是很容易自己编写:

function(weights)
  local sum = 0
  for _, v in next, weights do
    if v < 0 or math.floor(v) ~= v then
      error "权重必须是非负整数"
    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 "不应该出现这种情况。"
end
2014-11-11 00:06:40
用户12968803
用户12968803

尝试使用我的解决方案:

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) -- 只适用于整数权重
    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
end
2021-06-07 19:17:53