Once the table is shuffled, you just start using the numbers in order.
first time use mynumbers[1]. Next use mynumbers[2] until you run out of numbers. Then simply re-shuffle and start over at using [1] again.
Rob
Once the table is shuffled, you just start using the numbers in order.
first time use mynumbers[1]. Next use mynumbers[2] until you run out of numbers. Then simply re-shuffle and start over at using [1] again.
Rob
thanks for the code. this is an interesting trick to delete the selected item from the table…
i did not understand how it really work ? so when you delete the item… why the random function does not select the same index again…
if we assume the table has the following : 1,2,3,4,5… #numbers is 5
if num= 4 … then 4 will be removed from table… #numbers is 4
next time the random will select number between(1-4) … will the last number in the table (5) be shifted automatically to position 4…
this what i could not get… because if that is not the case then we should get nil some times.
Regards
Abdul
Do not forget about seed of rundom generator. If you do not specify new, then you will always use the same one and generaly each time you will get random but the same combination.
math.randomseed( os.time() ) ----> a different sequence each time if there is a long enough time between invocations
yeah but why we dont get nil value in this case… just to understand the algorithm if you have time :)
table.delete() removes the entry and those after it get moved to new locations. The table.delete() function is expensive due to all of this moving.
The best thing to do is to use a method called “shuffle”. This is like a deck of cards. You shuffle the list of numbers and then simply loop over the table 1 by 1. When you get to the end of the list, reshuffle. I personally use this function:
https://developer.coronalabs.com/code/shufflerandomize-tables
local mynumbers = {1, 2, 3, 4, 5, 6 }
table.shuffle( mynumbers )
for i = 1, #mynumbers do
print( mynumbers[i] )
end
thanks Rob for sharing the knowledge… how this function should work if you want to select 2 numbers form table without repeating them,
for example …
local mynumbers = {1, 2, 3, 4, 5, 6 }
x = 4
I want another two numbers (y and z) from the table but they should not equal to x and they should not be repeated.
regards
Abdul
Once the table is shuffled, you just start using the numbers in order.
first time use mynumbers[1]. Next use mynumbers[2] until you run out of numbers. Then simply re-shuffle and start over at using [1] again.
Rob