Randomizing Spots

Recently, I wanted to make a local script randomize the places of numbers for the client to go and hunt down but I’ve stumbled across a problem:

Code
local Spots = {1,2,3,4}

		for i = 1,4 do
			
			
			
			
			local Randomizer = math.random(1,#Spots)
			local part = game.Workspace.Numberz:FindFirstChild(tostring(Randomizer))
			local ChosenNum = game.Workspace.Numberz:FindFirstChild("Cloned"..string.sub(NumberCodeInString,i,i))
			
			
			print(game.Workspace.Numberz:FindFirstChild(tostring(Randomizer)))
			ChosenNum.Parent = game.Workspace.Numberz:FindFirstChild(tostring(Randomizer))
			
			ChosenNum.CFrame = CFrame.new(part.Position.X,part.Position.Y,part.Position.Z) * CFrame.fromEulerAnglesXYZ(math.rad(part.Orientation.X),math.rad(part.Orientation.Y),math.rad(part.Orientation.Z))
			
			
			table.remove(Spots,Randomizer)
			
			for i,v in pairs (Spots) do print (i,v) end
			
			
		end

Basically, what I want is so that once the block is positioned and parented onto the parts named “1”,“2” ect ect… , it deleted the “Spot” value that it took so another block can’t be placed in the same spot.

Issue:
When table.remove() is used, it messes up the ordering of the indexing (for example, if spot “2” was picked, it would delete the “2” in the array, but the index would show the following:
1 1
2 3
3 4
) then , on the line where it states local randomizer, the math.random value can be between 1 and 3 inclusive which means it can choose 2 again.

Is there a better way of doing this? ( sorry if this doesn’t make sense, not too great at explaining my code)

1 Like

Just use the value of the table, not the index.

local Randomizer = math.random(1,#Spots)
local randomNum = Spots[Randomizer]

You will have to modify the code to use the randomNum instead of the Randomizer variable

1 Like

Wont this get the same ish ending though? Both Randomizer and randomNum will be the same number, and when I go to remove said value from the table, I’ll end up with the same issue.

Randomizer will be a number 1-3. If you use it as the index in your Spots table, it’ll give you the value, not the index. Aka, in your example index 2 points to a value of 3. So if you input Randomizer as the index in the table, and Randomizer is 2, it’ll give you the value of index 2, which is 3.

Hope that makes sense

1 Like

Ooooh I see, thats smart! thanks!

1 Like