Jump to content

How to get a random choice from a table with Chances defined?


Recommended Posts

So , first of all we have a table from choices available

Quote

 

choices = {

    "First Item", -- index 1

    "Second Item", -- index 2

    "Third Item", -- index 3

}

 

what we should do if we wanna make another table that has the 70% Chance to get the "First Item" and 15% Chance for "Second Item" and 15% for "Third Item" ?

Link to post
  • Moderators

Hi. A solution if you give weight to items, so 1 weight = 1% chance.

local totalWeight = 100 -- SUM of weights

-- IMPORTANT, add items in ascending order by weights
local choices = {
    {"Second item", 15},
    {"Third item", 15},
    {"First item", 70},
}

function getRandomChoice()
    local randomWeight = math.random(totalWeight) -- get a random weight (between 1-100)
    -- loop trough table, and find which item is at the random weight. (for example, at the 20th position is "Third item")
    for i, choice in ipairs(choices) do
        if randomWeight <= choice[2] then
            return choice[1]
        end
        randomWeight = randomWeight - choice[2]
    end
end

I hope you understand it, but there is a video, it's C# but maybe helps: https://www.youtube.com/watch?v=OUlxP4rZap0

Edited by Patrick
  • Thanks 1
Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...