0

假设我有一张像这样的桌子:

skins = {desert_camouflage = 10, forest_camouflage = 20}

其中“desert_camouflage”的权重比“forest_camouflage”更稀有。

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

4

2 回答 2

1

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

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
于 2014-11-11T00:06:40.617 回答
1

试试我的解决方案:

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
end
于 2021-06-07T19:17:53.127 回答