shuffling a table

having a issue with shuffling values in a table

I’m using the following code

local function shuffle(t) local rand = math.random assert(t, "table.shuffle() expected a table, got nil") local iterations = #t local j for i = iterations, 2, -1 do j = rand(i) t[i], t[j] = t[j], t[i] end end

it shuffles the values in the table no problem but when I run the app on multiple devices at the same time it shows the values from the shuffled table in the same order

so for eg

table = {“a”, “b”, “c”, “d”, “e”}

shuffle(table)

output:

iDevice 1 = {“d”, “a”, “e”, “c”, “b”}

iDevice 2 = {“d”, “a”, “e”, “c”, “b”}

iDevice 3 = {“d”, “a”, “e”, “c”, “b”}

surely the shuffled table should be different for each one??

I’m really stumped on this, can anyone help me with a fix or a different way to code it??

You need to ‘seed’ your random number generator using math.randomseed().  Otherwise, math.random() will always produce the same values (useful if you want to have a consistent test case to play with).  Take a look at the Lua documentation of math.random on this page: http://lua-users.org/wiki/MathLibraryTutorial.

The most common way to seed the generator is by using the current time like this: math.randomseed(os.time).

(By the way, this concept is common across almost all programming languages, not just Lua.)

  • Andrew

so using

local rand = math.randomseed( os.time() )

should do the trick then?

Not quite.  First you set the random seed (usually somewhere near the start of your program), and then later you draw random numbers.  Like this:

[lua]

– Somewhere near the start of your program

math.randomseed( os.time() )   – This doesn’t return a value, and so there’s no reason to assign it to a variable

– … somewhere later in your program

local randomNumber = math.rand(10)   – Draw a random number from 1 to 10

[/lua]

  • Andrew

You need to ‘seed’ your random number generator using math.randomseed().  Otherwise, math.random() will always produce the same values (useful if you want to have a consistent test case to play with).  Take a look at the Lua documentation of math.random on this page: http://lua-users.org/wiki/MathLibraryTutorial.

The most common way to seed the generator is by using the current time like this: math.randomseed(os.time).

(By the way, this concept is common across almost all programming languages, not just Lua.)

  • Andrew

so using

local rand = math.randomseed( os.time() )

should do the trick then?

Not quite.  First you set the random seed (usually somewhere near the start of your program), and then later you draw random numbers.  Like this:

[lua]

– Somewhere near the start of your program

math.randomseed( os.time() )   – This doesn’t return a value, and so there’s no reason to assign it to a variable

– … somewhere later in your program

local randomNumber = math.rand(10)   – Draw a random number from 1 to 10

[/lua]

  • Andrew