A module for selecting a random item from a weighted list.
The API consists of a single function that accepts a dictionary where each key is an item that corresponds to a numeric weight indicating its likelihood of being chosen. The function returns the item (key) of the random selection.
VariantgetFromWeightedDictionary(DictionaryitemWeights)localRandomSelection=require(script.Parent.RandomSelection)
localitemWeights= {
item1=1; -- will be selected 20% of the timeitem2=2; -- will be selected 40% of the timeitem3=2; -- will be selected 40% of the time
}
localselectedItem=RandomSelection:getFromWeightedDictionary(itemWeights)
print(selectedItem) -- "item1", "item2", or "item3"The typical structure is a dictionary of item names and weights:
localitemWeights= {
item1=5;
item2=10;
item3=15;
}Any data type can be used, although strings are strongly recommended.
localitems=script.Parent.ItemsFolderlocalitemWeights= {
[items.Item1] =5;
[items.Item2] =10;
[items.Item3] =15;
}
localselectedItem=RandomSelection:getFromWeightedDictionary(itemWeights)
selectedItem:Clone()localitemWeights= { 5, 10, 15 }
localselectedItem=RandomSelection:getFromWeightedDictionary(itemWeights)
print(itemWeights) -- 1, 2, or 3Decimal weight values can be used.
localitemWeights= {
item1=0.1;
item2=0.6;
item3=0.7;
}Empty arrays will throw errors.
localitemWeights= {}
-- the following line will error:RandomSelection:getFromWeightedDictionary(itemWeights)