# Weighted Luck System Picking Top Item

For my weighted luck system I just loop through every collectable in my game and store it inside a table, then I sort the table keys because the item data is inside a hashmap and I don’t want to randomly go through the table as that would produce weird results. The issue is that when there is luck involved it’s going to pick the top item each time.

Example:
common = 100
uncommon = 1
rare = 1
total = 102
random = 60 --random number
luck = 2
number = random * luck (60 * 2) = 120
clamp number to total (120 clamps to 102)
102 is going to pick rare 100% of the time even though rare and uncommon are the same rarity and thats the issue im having.

``````local collectables = {}
local totalChance = 0

for itemName, itemData in next, Items do
if not itemData.Collectable then continue end
collectables[itemName] = itemData
totalChance += itemData.SpawnChance
end

local sortedCollectables = {}
for key, _ in next, collectables do
table.insert(sortedCollectables, key)
end

table.sort(sortedCollectables, function(a, b)
return collectables[a].SpawnChance > collectables[b].SpawnChance
end)

local luckMultiplier = 1 + collectableSpawn:GetAttribute("LuckMultiplier")
local randomNumber = math.min(math.random(1, totalChance) * luckMultiplier, totalChance)
local selectedCollectable = nil

totalChance = 0
for _, collectableName in next, sortedCollectables do
local collectableData = collectables[collectableName]
totalChance += collectableData.SpawnChance

if totalChance >= randomNumber then
selectedCollectable = collectableName
break
end
end
``````

how my item database is setup

``````["Bronze Ring"] = {
["Type"] = "Trinket",
["StackLimit"] = 99,
["Sellable"] = true,
["Collectable"] = true,
["SpawnChance"] = 10000,
["Worth"] = 2
},

["Bronze Goblet"] = {
["Type"] = "Trinket",
["StackLimit"] = 99,
["Sellable"] = true,
["Collectable"] = true,
["SpawnChance"] = 9500,
["Worth"] = 3
},
``````

if you know a way to midigate this please let me know!