Weighted Collection System!
Weighted collection aims to provide an easy way for random distribution. Like if you open a chest and have some items that you want to randomly award the player.
API
WeightedCollection.new()
Creates a new weighted collection objected.
WeightedCollectionObject:Add(data: any, weight: number)
Adds whatever data you pass in into the collection with the given weight. The higher the weight the more likely for that item to be picked.
WeightedCollectionObject:Remove(data: any)
Removes the data from the collection.
WeightedCollectionObject:GetRandom(amount: number?)
Returns random data from the collection or a table of random data if amount is greater than 1.
WeightedCollectionObject:GetTotalWeight()
Returns how much weight the collection has.
WeightedCollectionObject:SetLuck(luckMultiplier: number)
Sets the collection luck multiplier. The higher the luck multiplier the more common it is for data with a lower weight to be picked.
WeightedCollectionObject:Clear()
Clears all the collection.
WeightedCollectionObject:Destroy()
Cleans up the collection.
Example
local WeightedCollection = require(script.WeightedCollection)
-- Create the collection
local myCollection = WeightedCollection.new()
-- Add rarities to the collection wth weights
myCollection:Add("Common", 100_000)
myCollection:Add("Uncommon", 90_000)
myCollection:Add("Rare", 50_000)
myCollection:Add("Epic", 10_000)
myCollection:Add("Legendary", 1_000)
myCollection:Add("Mythical", 1)
-- Print out 100x data with luck multiplier of 1x
print("----------| Normal Luck |----------")
for _, rarity in next, myCollection:GetRandom(100) do
print(rarity)
end
-- Print out 100x data with luck multiplier of 100x
myCollection:SetLuck(100)
print("----------| Great Luck |----------")
for _, rarity in next, myCollection:GetRandom(100) do
print(rarity)
end
-- Print out 100x data with luck multiplier of 0.5x
myCollection:SetLuck(0.5)
print("----------| Bad Luck |----------")
for _, rarity in next, myCollection:GetRandom(100) do
print(rarity)
end
-- Removes common, uncommon, and rare from the collection
myCollection:Remove("Common")
myCollection:Remove("Uncommon")
myCollection:Remove("Rare")
-- Gets the total weight of the collection
print(myCollection:GetTotalWeight())
-- Clears the collection
myCollection:Clear()
-- Cleans up the collection
myCollection:Destroy()
Download
You can download the model from this link.