Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
3

Changing the probability of something being chosen?

Asked by
Klink45 20
8 years ago
Edited 8 years ago

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)]
0
From the looks of it, that's the best way Scootakip 299 — 8y
1
No, it's not. I'll work on an answer. ScriptGuider 5640 — 8y

1 answer

Log in to vote
0
Answered by 8 years ago
Edited 8 years ago

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/!

Ad

Answer this question