Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Changing the probability of something being chosen?

I want to make it so some things in my table have a higher probability of being chosen than others. I currently achieve this by putting things in the table multiple times, but I was wondering if there was a better way?

local weather = {"Rain", "Rain", "Rain", "Snow", "Snow", "Sunny", "Sunny", Sunny", "Sunny"}
local selectedweather = weather[math.random(1, #weather)]

2 comments

0

From the looks of it, that's the best way

1

No, it's not. I'll work on an answer.

1 answer

What I ended up with was a dictionary where you could specify how many times you want that weather type to be added to the weather list.

Useful Links:

http://wiki.roblox.com/index.php?title=Function_dump/Table_manipulation http://wiki.roblox.com/index.php?title=Table#Dictionaries

local weatherRaw = {
	["Rain"] = 3;
	["Snow"] = 2;
	["Sunny"] = 4;
}

function selectWeather()
	local weatherList = {}
	for (key, value in pairs(weatherSettings)) do
		for (i = 1, value) do
			table.insert(weatherRaw, #weatherRaw + 1, key)
		end
	end
	return weatherRaw[math.random(1, #weatherList)]
end

local currentWeather = selectWeather()

The selectWeather function gets the weather name, and how many times you want it to be added to the list. It then adds each weather type the specified number of times and returns a random one.

In essence, it is almost exactly the same as:

local weather = {"Rain", "Rain", "Rain", "Snow", "Snow", "Sunny", "Sunny", Sunny", "Sunny"}
local selectedweather = weather[math.random(1, #weather)]

That is, except for the fact that it is more automated, and quite a bit less messy.

If you found my solution helpful, consider leaving an upvote and accepting my answer. Also, check out my website: http://robloxguides.com/!

This discussion is preserved as it was. New answers, comments, and votes are closed.