Table Randomizer

  1. What do you want to achieve?
    Hello, I am trying to achieve a table that randomly sorts everything within itself.

  2. What is the issue?
    I Cant figure out how, if I knew I wouldn’t be asking.

  3. What solutions have you tried so far?
    Looking on the dev forum but all the other ones are just choosing a random value from a table, I just want the entire table mixed up to keep values from being in order. Probably using math.random with table.sort in some way.

This is probably something really easy and I just am not seeing it.

Basically I am getting the parts in a model but they are all sorted out in the table. I just want the table to have them randomized so when I put them into separate tables later they aren’t being added in the pre set order, I just want it to be sorted into a completely random order. Sorry if I am not clear about what I am asking, please feel free to ask for clarification on what you are confused about.

local function shuffle(t)
    local new = {}

    while #t > 0 do
        table.insert(new, table.remove(t, math.random(1, #t)))
    end

    return new
end

local t = {"a","b","c","d"}
for i = 1, 5 do
    print(table.concat(shuffle(t), ", ")) --> d, b, c, a
end
2 Likes

You can try something like this:

local UnsortedTable = {
	"Cheese",
	"Strawberries",
	"Nuts",
	"Plutonium",
	"Nuclear Missile",
	"Waffles",
	69420
}

local function ReturnSortedTable(TableToSort)
	local SortedTable = {}
	local RandomChosenValue -- for scope
	for i = 1, #UnsortedTable, 1 do
		repeat
			RandomChosenValue = UnsortedTable[math.random(1, #UnsortedTable)]
		until not table.find(SortedTable, RandomChosenValue)
		table.insert(SortedTable, RandomChosenValue)
	end

	return SortedTable
end

print(ReturnSortedTable(UnsortedTable))

We get a random value from the unsorted table, we make sure it was not in the sorted table before and then insert it into the sorted table. Then once we’re done with all the values, we return it and print it.

Shoutout to @bluebxrrybot, his solution was shorter and more complex (more complex to me)

2 Likes

Yep, I had to make a new table and just get a random value and insert it into a new table. I thought there would have been some way to just randomly sort it using the sort function, but this still gets the job done, Thank you.

1 Like

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