Random Generator Stopping Repeats of Levels [SOLVED]

I am trying to make a tower ish generator that does not repeat the levels that are before it (e.g. 1,1)

I have tried a couple thing to fix it and have managed to make it so that any duplicates are pushed to the side like the picture, but I am unsure how to fill in those gaps once it excludes the duplicates.

Test

After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!

function Generator()
	local stages = game.ReplicatedStorage:WaitForChild("Stages"):GetChildren()
	local start = workspace.EndPart

	local amount = math.random(7,12)
	print(amount)
	local previousStage = start
	
	
	for i= 1, amount,1 do
		local StageChoosed = game.ReplicatedStorage.Stages:GetChildren()[math.random(1, #stages)]:Clone()
		StageChoosed.Parent = game.Workspace.StageGenerated
		print(StageChoosed)
		
		if StageChoosed.Level.Value == previousStage.Level.Value then
			StageChoosed = game.ReplicatedStorage.Stages:GetChildren()[math.random(1, #stages)]:Clone()
		end
		
		StageChoosed:SetPrimaryPartCFrame(
			previousStage.Center.CFrame + Vector3.new(0,17.28,0)
		)
		
		previousStage = StageChoosed
		
	end

	local Endstage = game.ReplicatedStorage.StartPart:Clone()
	Endstage.Parent = game.Workspace.StageGenerated

	Endstage:SetPrimaryPartCFrame(
		previousStage.Center.CFrame + Vector3.new(0,17.28,0)
	)

end

You can remove it from the table of stages once it’s selected. I’ve also fixed some other minor issues.

function Generator()
	local stages = game.ReplicatedStorage:WaitForChild("Stages"):GetChildren()
	local start = workspace.EndPart

	local amount = math.random(7, 12)
	print(amount)
	local previousStage = start


	for i = 1, amount do
		local randIndex = math.random(1, #stages)
		if stages[randIndex] then
			local StageChoosed = stages[randIndex]:Clone()
			table.remove(stages, randIndex) --removes it so it can't be picked again
			StageChoosed.Parent = game.Workspace.StageGenerated
			print(StageChoosed)

			StageChoosed:SetPrimaryPartCFrame(
				previousStage.Center.CFrame + Vector3.new(0, 17.28, 0)
			)

			previousStage = StageChoosed
		end
	end

	local Endstage = game.ReplicatedStorage.StartPart:Clone()
	Endstage.Parent = game.Workspace.StageGenerated

	Endstage:SetPrimaryPartCFrame(
		previousStage.Center.CFrame + Vector3.new(0, 17.28, 0)
	)
end

I’m getting the error ‘ServerScriptService.RoundScript:28: invalid argument #2 to ‘random’ (interval is empty)’ now, thanks for the help also btw

That means that #stages is returning 0.
Is the model/folder in ReplicatedStorage empty?

Oh yeah it is, I have 5 stages at the moment so I think if I make I make the amount between 1-5 it should work fine, I will test that now though.