Shuffling

General discussion about LÖVE, Lua, game development, puns, and unicorns.
User avatar
Boolsheet
Inner party member
Posts: 780
Joined: Wed Dec 29, 2010 4:57 am
Location: Switzerland

Re: Shuffling

Post 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
Shallow indentations.
User avatar
micha
Inner party member
Posts: 1083
Joined: Wed Sep 26, 2012 5:13 pm

Re: Shuffling

Post 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.
User avatar
bartbes
Sex machine
Posts: 4946
Joined: Fri Aug 29, 2008 10:35 am
Location: The Netherlands
Contact:

Re: Shuffling

Post 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).
Post Reply

Who is online

Users browsing this forum: varpeti and 6 guests