How to make a weighted RNG in ROBLOX Lua? (Like CS:GO cases)

1.4k views Asked by At

Say I have a table like:

skins = {desert_camouflage = 10, forest_camouflage = 20}

Where "desert_camouflage" is weighted rarer than "forest_camouflage".

I am searching for a Rbx.Lua RNG function that will print it's result.

2

There are 2 answers

2
Deduplicator On BEST ANSWER

I don't think so, but it's easy to write yourself:

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
0
darkfrei On

Try my solution:

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