How To Improve This Easy Line of Code?

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)

I have seen this post, but honestly, It just confuses me, and I have no idea how to apply it to my own system https://scriptinghelpers.org/questions/19757/doing-things-by-chance-rather-than-mathrandom

Thanks in advance

2 Likes

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.

2 Likes

It is funny, because I searched everywhere (it felt like) for a solution, but never found that article. Thanks for the help :slight_smile:

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
1 Like