Weighted Chance System (WITH LUCK!)

Making a weighted chance system is pretty easy, but adding luck to it? A bit difficult.
I decided to open source my weighted chance system which also includes my implementation of luck.

FOR A DETAILED EXPLANATION OF A WEIGHTED CHANCE SYSTEM CHECK OUT THIS POST! Weighted Chance System

Heres the source code :

local Module = {}

function Module:GetItem(Luck : number?)
	if Luck then
		local Best = Module:GetItem()
		
		for i = 1, Luck - 1 do
			local New = Module:GetItem()
			if Best.Rarity < New.Rarity then
				Best = New
			end
		end
		
		return Best
	end
	
	local Counter = 0

	for _, v in Rarities do
		Counter += 1 / v.Rarity
	end

	local Chosen = Random.new():NextNumber() * Counter
	local Weight = 0

	for _, v in Rarities do
		Weight += 1 / v.Rarity

		if Weight >= Chosen then
			return v
		end
	end
end

return Module

Make SURE to add a Rarities variable which contains all your rarities.

10 Likes

right soo… this post atleast explains something

3 Likes

Ill link that post in the main post since im too lazy to explain what this does :stuck_out_tongue:

really the only downside with this is luck being based off of iterations.

Yea, thats the downside, a lot of luck would cause perfomance issues.

what can i do to make it support larger amounts of luck?

sorry 4 bump

Probably counting the total weight beforehand could make it ~2x faster and also making this parallel. That’s another 8x performance boost depending on your cpu.