Hello All,
I have made this terrible table, and a simple statement to get a random value in it. It works, but seems (and looks) to be a horrid way of doing this. This is for a random chance system. How would I change this, so it does the same exact thing, but nicer? Is there a way to improve its functionality? Thank you!
Code:
local list = {"Red", "Red", "Red", "Blue", "Blue", "Green"} --the "Chance" each object has is determined by how many times it is entered. Not very efficient seeming.
local index = math.random(#list)
print(index)
There are some great explanations to this exact problem in another thread.
I’m guessing you want to figure out how to do like 50% chance without having to enter half of the list being a certain string.
This has all the examples and some of the authors of the replies are way better at explaining some of the code than I am, but if you need any help - feel free to reply back or private message me.
I don’t know that I’d call this improving your perfectly fine code, but this is how I would make it more complicated:
local dictionary = {
"Red" = 3,
"Blue" = 2,
"Green" = 1
} --the "Chance" each object has is determined by weight number
local weight = 0
for key, value in pairs(dictionary) do --find total weight of 'list'
weight = weight + value
end
local index = math.random(weight)
weight = 0
for key, value in pairs(dictionary) do --find 'winner'
weight = weight + value
if weight >= index then
print(key)
end
end
aka, how to turn 3 lines into 20 to get the same result.
Thanks for the help! I ended up doing something like this
local R = Random.new()
local weightedItems = {
Red = 20,
Blue = 90,
Green = 5,
Purple = 5
}
local function getRandomItem(weightedItems)
local sum = 0
for _,weight in pairs(weightedItems) do
sum = sum + weight
end
local rand = R:NextNumber(0, sum)
local found
for item, weight in pairs(weightedItems) do
rand = rand - weight
if rand < 0 then
found = item
print(found)
break
end
end
return found
end