Issues with weighted odds

Hello! I’m having an issue where when I run this code it always picks common. Even changed the odds, nothing works. No errors, just this piece of code in SSS.

while true do
	task.wait(math.random(10, 15))
	if game.Workspace:FindFirstChild("CandyApple") then
		game.Workspace.CandyApple:Destroy()
	end
	local clone = game.ReplicatedStorage.CandyApple:Clone()
	clone.Parent = game.Workspace
	poses = {
		"-253.25, 36.506, -6.25",
		"-283.25, 36.125, -11.75"
	}
	local num = poses[math.random(1, #poses)]
	print(num)
	clone:MoveTo(num)
	
	local colors = {
		["Common"] = {Color3.fromRGB(196, 40, 28)};
		
		["Rare"] = {Color3.fromRGB(132, 222, 110)};
		
		["Legendary"] = {Color3.fromRGB(255, 247, 0)};
		
	}
	
	local rarities = {
		["Common"] = 60;
		
		["Rare"] = 30;
		
		["Legendary"] = 10;
	}
	
	local number = math.random(1, 100)
	
	local counter = 0
	
	for rarity, weight in pairs(rarities) do
		counter = counter + weight
		
		if number <= counter then
			local rarityTable = colors[rarity]
			local chosenColor = rarityTable[math.random(1,#rarityTable)]
			
			print(chosenColor)
			
			clone.Part.Color = chosenColor
		end
	end
end

I think it should just be adding a break in the for loop.

local rarities = {
	["Common"] = 60;

	["Rare"] = 30;

	["Legendary"] = 10;
}


for i = 1, 100 do
	local counter = 0
	for rarity, weight in pairs(rarities) do
		counter = counter + weight

		if i <= counter then
			print(i..", "..rarity)
			break
		end
	end
end

This is the code I tried and it printed the rarities correctly.
So just add the break in the for loop like this

for rarity, weight in pairs(rarities) do
	counter = counter + weight
		
	if number <= counter then
		local rarityTable = colors[rarity]
		local chosenColor = rarityTable[math.random(1,#rarityTable)]
			
		print(chosenColor)
			
	    clone.Part.Color = chosenColor
        break
	end
end
1 Like

The method MoveTo only excepts Vector3 quantity’s not string’s so you will have to rewrite that as a Vector3.