Randomize order in dictionary

I’m trying to randomize the order in which values are keyed.

Basically, this dictionary:

local td = {
[1] = "One",
[2] = "Two",
[3] = "Three",
[4] = "Four",
[5] = "Five",
[6] = "Six",
[7] = "Seven",
[8] = "Eight"
}

has to be randomized so it looks something like this:

local td = {
[1] = "Six",
[2] = "Four",
[3] = "Five",
[4] = "Seven",
[5] = "Eight",
[6] = "Three",
[7] = "One",
[8] = "Two"
}

The values must not be in the dictionary twice or be void.



I tried doing the following but it didn’t work properly:

local function RandomizeDictAsync(OriginalDict)
	local NewDict = {}

	local OriginalDictSize = #OriginalDict

	for Index, Value in pairs(OriginalDict) do
		repeat
			local NewRandomIndex = math.random(1, OriginalDictSize)

			if not NewDict[NewRandomIndex] then
				NewDict[NewRandomIndex] = Value
			end

			task.wait(.01)
		until #NewDict == OriginalDictSize
	end

	return NewDict
end

Does anyone know how I can do this?

Here, I gotchu :slight_smile:

local td = {
	[1] = "One",
	[2] = "Two",
	[3] = "Three",
	[4] = "Four",
	[5] = "Five",
	[6] = "Six",
	[7] = "Seven",
	[8] = "Eight"
}

function RandomizeTD ()
	local CloneTD = {}
	local NewTD	= {}
	
	for i, v in pairs(td) do
		table.insert(CloneTD, v)
	end
	for i, v in pairs(td) do
		local Index = math.random(1, #CloneTD)
		
		NewTD[i] = CloneTD[Index]
		table.remove(CloneTD, Index)
	end
	
	return NewTD
end
3 Likes