How to configure the correct logic for choosing a random item from a list based on a rarity item ie "rare" "normal",

I am writing a game using the Corona SDK in lua. It is not easy for me to come up with logic for such a system;

I have different things. I want some items to have a 1/1000 chance to be selected (unique item), I want some to have 1/10, some 2/10, etc.

I was thinking of filling out a table and choosing a random item. For example, I would add 100 "X" elements to the table, and not 1 "Y". Therefore, choosing randomly from [0,101], I kind of get what I want, but I was wondering if there are other ways to do this.

+4
source share
2
items = {
    Cat     = { probability = 100/1000 }, -- i.e. 1/10
    Dog     = { probability = 200/1000 }, -- i.e. 2/10
    Ant     = { probability = 699/1000 },
    Unicorn = { probability =   1/1000 },
}

function getRandomItem()
    local p = math.random()
    local cumulativeProbability = 0
    for name, item in pairs(items) do
        cumulativeProbability = cumulativeProbability + item.probability
        if p <= cumulativeProbability then
            return name, item
        end
    end
end

, 1. , ( ), . 1/10 100/1000: , , .


, :

local count = { }

local iterations = 1000000
for i=1,iterations do
    local name = getRandomItem()
    count[name] = (count[name] or 0) + 1
end

for name, count in pairs(count) do
    print(name, count/iterations)
end
+5

, - .

local chancesTbl = {
    -- You can fill these with any non-negative integer you want
    -- No need to make sure they sum up to anything specific
    ["a"] = 2,
    ["b"] = 1,
    ["c"] = 3
}

local function GetWeightedRandomKey()
   local sum = 0
   for _, chance in pairs(chancesTbl) do
      sum = sum + chance
   end

   local rand = math.random(sum)
   local winningKey
   for key, chance in pairs(chancesTbl) do
      winningKey = key
      rand = rand - chance
      if rand <= 0 then break end
   end

   return winningKey
end
0

Source: https://habr.com/ru/post/1539067/


All Articles