Table sorting giving mixed outputs

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