How to not get duplicates when choosing random maps?

  1. What do you want to achieve? Keep it simple and clear!
    I want to make sure my script doesnt make duplicates

  2. What is the issue? Include screenshots / videos if possible!
    I don’t know how

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I have tried YT and Devforum

Here is my code :

for i,v in pairs(script.Parent:GetChildren()) do
		if v:IsA("Model") then
			local chosenMap = maps[math.random(1,#maps)]
			v.Name = chosenMap
			v.GuiPart.SurfaceGui.NameLabel.Text = chosenMap
			local voteName = Votes:FindFirstChild(v.Name)
			voteName = chosenMap
			local vote = Instance.new("IntValue")
			vote.Name = chosenMap
			vote.Parent = Votes
		end
	end
1 Like

Create a clone of the maps table and remove the chosen map from the cloned maps table.

tempmaps = table.clone(maps)
for i,v in pairs(script.Parent:GetChildren()) do
	if v:IsA("Model") then
		local chosenIndex = math.random(#tempmaps) -- Minimum is defaulted to 1 with only one parameter
		local chosenMap = tempmaps[chosenIndex]
		table.remove(tempmaps, chosenIndex)
		v.Name = chosenMap
		v.GuiPart.SurfaceGui.NameLabel.Text = chosenMap
		local voteName = Votes:FindFirstChild(v.Name)
		voteName = chosenMap
		local vote = Instance.new("IntValue")
		vote.Name = chosenMap
		vote.Parent = Votes
	end
end

Hopefully that works! Just make sure you have equal or more maps than you do voting spots, otherwise it will error.

2 Likes

You could do something like:

local CurrentMap = (...) --whatever map you currently have up is

local MaxLoop = 50 --make sure we dont timeout
local chosenMap = maps[math.random(1,#maps)]

local CurrentLoopOver = 0
while chosenMap == currentMap and CurrentLoopOver < MaxLoop do
   chosenMap = maps[math.random(1,#maps)]
   CurrentLoopOver += 1
end

You’d have a (1/n)^50 chance (where is the amount of maps >1) to get the same map.
Or, much more simply, you could just exclude the current map from the maps list.

Edit: the post above should be marked as the solution

1 Like

OMG thanks it worked! I can now continue with my map voting system :smiley:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.