Code: Select all
-- Should error after a few iterations.
sortFunction = function() return math.random()>math.random() end
while true do t={1,2,3,4} table.sort(t, sortFunction) end
Code: Select all
-- Should error after a few iterations.
sortFunction = function() return math.random()>math.random() end
while true do t={1,2,3,4} table.sort(t, sortFunction) end
Boolsheet is correct. This method has a flaw:Kyle wrote:An even simpler way, using Lua's built-in table.sort.Code: Select all
table.sort(t, function() return math.random()>math.random() end)
The clean, unbiased way of doing it, is assigning each entry in the table a fixed random number. That makes the whole difference. Implementationwise this makes the code a bit longer again and you have to create an additional table. On the other hand (according to Wikipedia) it seems more robust against badly generated random numbers.A variant of the above method that has seen some use in languages that support sorting with user-specified comparison functions is to shuffle a list by sorting it with a comparison function that returns random values. However, this is an extremely bad method: it is very likely to produce highly non-uniform distributions, which in addition depends heavily on the sorting algorithm used.
Users browsing this forum: varpeti and 6 guests