Table sorting giving mixed outputs

Problem

Using code below to randomize a table the output either errors or executes. Running it multiple times gives mixed results (errors or executes without error). Can someone explain why this is happening?

Code

local t={1,2,3,4,5,6} 
table.sort(t,function(a,b)
    return Random.new():NextNumber() < 0.5 
end) 
table.foreach(t,print)
2 Likes

You should use the Knuth algorithm to randomize arrays.

Here is a Lua interpretation:

local rng = Random.new(os.time())

local function shuffle(array)
	local item
	for i = #array, 1, -1 do
		item = table.remove(array, rng:NextInteger(1, i))
		table.insert(array, item)
	end
end

Basically this version goes backward from the end, picks a random element, and pushes it to the end of the array. This guarantees that no elements are shuffled more than once.

3 Likes

why is the method I’m using wrong?

If you pass a function into table.sort then the result of that comparator has to be consistent for each table element. i.e. if a < b evaluates to true then a >= b MUST evaluate to false, otherwise you will get the “invalid order function for sorting” error. This consistency can never be guaranteed if you use a comparator that returns true or false randomly.

4 Likes

Thank you, the method you linked works.