[Module]: Weighted Random - Get Random Items Based on Chances

Get Here:

How to use?

Hi! I made this module to help developers easily pick random items with different chances. You can use it to create systems like MM2’s murderer selection or Pet Sim’s egg-opening mechanics.

It works by taking a dictionary where each key is assigned a numerical chance, and then outputs a random value based on those chances. For example:

local exampleDict = {
	["Pet1"] = 0.1,   --10% chance
	["Pet2"] = 0.1,   --10% chance
	["Pet3"] = 0.2,   --20% chance
	["Pet4"] = 0.6,   --60% chance
}

-- outputs random key: (Pet1, Pet2, etc...)
WeightedRandom.pickRandom(exampleDict)  

These values do not need to be in numerical order or add up to 1, as the module handles that for you! This means you can use dictionaries with any positive numbers! For example:

local exampleDict = {
	["Pet1"] = 100,  --55.56% chance
	["Pet2"] = 30,   --16.67% chance
	["Pet3"] = 40,   --22.22% chance
	["Pet4"] = 10,   --5.56% chance
}

How to Get Normalized Dictionary?

You can also get these normalized value by using the function ‘.normalizeDictionary()’
Call the function and input the desired dictionary:

WeightedRandom.normalizeDictionary(exampleDict)

Output:
image

8 Likes

So wait, 0.3 will always be equal to 30%?

No, the module will automatically adjust the percentage chance based on the other items in the dictionary. For example if the dictionary had only 1 key with value of 0.3, then it will have a 100% chance of being chosen.

-- Since theres only 1 value here, 'Pet1' will have a 100% chance of being chosen
local exampleDict = {
	["Pet1"] = 0.3,   --100% chance
}
-- Module will automatically adjust values
local exampleDict2 = {
	["Pet1"] = 0.3,   --50% chance
        ["Pet2"] = 0.3   --50% chance
}

if however the values of all keys add up to 1 then the module will leave them as is

local exampleDict = {
	["Pet1"] = 0.1,   --10% chance
	["Pet2"] = 0.1,   --10% chance
	["Pet3"] = 0.2,   --20% chance
	["Pet4"] = 0.6,   --60% chance
}

Let me know if you have any more questions :slight_smile:

oops, i see the confusion now, I edited the post. Hopefully that clears up everything. I accidenly labeled 0.3 instead of 0.6

so then:

local exampleDict = {
	["Pet1"] = 0.1,   
	["Pet2"] = 0.1,   
	["Pet3"] = 0.1,    
	["Pet4"] = 0.1,    
}

that means all pets have a 25% chance, right?

yes, that is correct. THe module will automatically adjust it :))

I see I see, thats pretty nice! :+1:

1 Like