Page 2 of 2

Re: Shuffling

Posted: Fri Mar 22, 2013 5:30 am
by Boolsheet
That's the thing with random numbers; you can never be sure. :P

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

Re: Shuffling

Posted: Fri Mar 22, 2013 9:02 am
by micha
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)
Boolsheet is correct. This method has a flaw:
While this look really elegant, it is biased. See the section "Comparison with other shuffling algorithms" on Wikipedia. It says:
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.
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.

Re: Shuffling

Posted: Fri Mar 22, 2013 9:32 am
by bartbes
Yeah, as Boolsheet mentioned, table.sort should error if it does that, since it requires your sort function to be deterministic, and it can actually find out (and complain).