Creating Chance

How would I go about creating a % of something to happen for example

10% to print “Hello”

30% to print “Goodbye”

70% to print “Hahahaha”

Although it does not give 100% it works the same

local Percentages = {
	["Hello"] = 10,
	["Goodbye"] = 30,
	["Hahahaha"] = 70,
}
local Table = {}
for Text, Percentage in pairs(Percentages) do
	for _ = 1, Percentage do
		table.insert(Table, Text)
	end
end

local random = Table[math.random(#Table)]
print(random)

Sources:
math.random
table

1 Like

What do you mean it does not give 100%?

10 + 30 + 70 gives 110, only that

local Hello = NumberRange.new(0,10)
local Goodbye = NumberRange.new(11,41)
local Hahahaha = NumberRange.new(42,112)
local rand = math.random(1,112)

if rand == Hello then
    print("Hello")
elseif rand == Goodbye then
    print("Goodbye")
elseif rand == Hahahaha then
    print("Hahahaha")
end

Haha oops! Thank you very much!

You should use weighted random instead of the provided solution, such as this:

local weights = {
	
	["Hello"] = 10; -- 10/110
	["Goodbye"] = 30; -- 30/110
	["Hahahaha"] = 70 -- 70/110
	
}

local function PickRandom()
	
	-- Get Total Weight Of All Items
	
	local weight = 0
	
	for l,v in pairs(weights) do
		weight += v
	end
	
	-- Pick Random Number Between 0 and Weight
	
	weight = math.random(weight)
	
	-- Iterate And Minus Weight, Return when weight <= 0 
	
	for l,v in pairs(weights) do
		weight -= v
		
		if weight <= 0 then
			return l
		end
		
	end
	
	
end


print(PickRandom())
2 Likes