Generate random sequence of 4 numbers?

Can anybody explain me how to generate a random sequence of 4 numbers?

Like:

3,2,1,4
4,2,1,3
2,3,1,4

etc

Must be simple, but i’m either to stupid or to tired lol

[import]uid: 50459 topic_id: 16920 reply_id: 316920[/import]

math.randomseed(os.time())  
  
local function generateFourRandomNumbers()  
 local myString = ""  
 for i = 1, 4 do  
 myString = myString .. math.random(4) .. ","   
 end  
 print(myString) -- okay you're left with a extra ,  
end  
  
for i = 1, 4 do  
 generateFourRandomNumbers()  
end  

[import]uid: 19626 topic_id: 16920 reply_id: 63437[/import]

Wow, that was fast :slight_smile:

Sorry i forgot to mention, any number cannot occur twice, and thats what happens with this code.

[import]uid: 50459 topic_id: 16920 reply_id: 63439[/import]

then reject the number. check the new random number against a table. if the number is already in the table, reject, and generate a new number until it satisfies the eq.

c. [import]uid: 24 topic_id: 16920 reply_id: 63443[/import]

I got it:

local function generateFourRandomNumbers()  
 local myString = ""  
 repeat  
 Choice = math.random(4)  
 if string.find(myString, Choice) == nil then  
 myString = myString .. Choice   
 end   
 until string.len(myString) == 4  
 print(myString)   
end  
  
math.randomseed(os.time())  
  
generateFourRandomNumbers()  

Thanks for the help rob! [import]uid: 50459 topic_id: 16920 reply_id: 63442[/import]

Actually what you are tying to do is “Shuffle” the numbers.

You should search the forums for “shuffle”, there have been several forum posts lately on how to shuffle a table.

local numbers = {1, 2, 3, 4}  
  
local function shuffleTable(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  
  
shuffleTable(numbers)  

[import]uid: 19626 topic_id: 16920 reply_id: 63454[/import]

I think Rob kind of nailed it much better, you do not need random numbers but you need shuffling of a fixed array.

you can read a bit more on shuffling here http://howto.oz-apps.com/2011/09/tables-part-2.html

cheers,

?:slight_smile: [import]uid: 3826 topic_id: 16920 reply_id: 63488[/import]