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
Label: corona android iphone ipad building error inmobi problem display screen View image tableView failed object physics touch button game lua config event listener |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 |
Wow, that was fast :)
Sorry i forgot to mention, any number cannot occur twice, and thats what happens with this code.
I got it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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() |
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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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) |
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,
?:)