Probability dictionary

If i make a dictionary (example below)

local situations = {
    landed = 85,
    cancelled = 14,
    crashed = 1
}

how would I make a script that prints the situation with the corresponding chance (out of 100)?

Please expand your question, it is not possible to understand what you want.

For example, if i made a script that picked a random number from 0 to 100, and if it was under 1 it would be crashed, 14 would be cancelled, and 85 would be landed

if this is what you mean, it should work. it returns the table of probabilities for all situations. (the probabilities returned should be a range from 0 to 1)

local situations = {
	["landed"] = 85,
	["cancelled"] = 14,
	["crashed"] = 1,
}

local function calculateChance()
	local allSituations = 0
	local situationsProbability = {}
	
	for _,v in pairs(situations) do
		allSituations += v
	end
	
	for i,v in pairs(situations) do
		situationsProbability[i] = v/allSituations
	end
	
	return situationsProbability
end

print(calculateChance())

made this code in a rush, clean it up as you please
(also idk what i’m doing procrastinating on the devforum, i should be doing something else rn)

4 Likes

Just to complete what @AkariInsko posted, the way you’d actually get a random value from the table based on those probabilities is this:

local function calculateChance(situations)
	local allSituations = 0
	local situationsProbability = {}
	
	for value, probabilityFactor in pairs(situations) do
		allSituations += probabilityFactor 
	end
	
	for value, probabilityFactor  in pairs(situations) do
		situationsProbability[value] = v / probabilityFactor  --Changed to be a value-to-probability dictionary instead of an array
	end
	
	return situationsProbability
end

local function getRandomByDistribution(valuesProbabilityDistribution)
    local r = math.random()
    
    local lastValue

    --Return the first value whose probability is >= r
    for value, probability in pairs(valuesProbabilityDistribution) do
        if r < probability then -- E.g. if prob is 0.1, there is 0.1 chance of picking it
            return value
        end
        lastValue = value
    end
    
    --Might be unnecessary. Guarantees that *something* gets picked, 
    -- which might not happen if the probabilities add up to less than 1 
    -- because of floating point error or whatever.
    return lastValue
end

print(getRandomByDistribution(calculateChance(situations))) --Should print landed 85% of the time

Note that your probability factors don’t actually need to add up to 100 for this to work with their method (or this one), it can be anything. Which is a lot more convenient because getting that to work with a lot of different possibilities can get complicated quickly.

1 Like