0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
The first time i click on the CREATE_NUMBER the function will return (random) a number lets say(for example) it returns the number 2. The second time i click on the CREAT_NUMBER i want the range of numbers will be: 0, 1, 3, 4, 5, 6, 7, 8, 9, 10 (without the number 2). Lets say the second click returns the number 6, so the remaining numbers will be: 1, 3, 4, 5, 7, 8, 9, 10. At the end i ll take a random sequence of numbers for example:
2, 6, 3, 8, 4, 1, 9, 5, 10, 9, 7, 0.
At the twelfth click i would like the restart of the function using all the numbers.
I wrote some code and works but i dont think is very good solution:
Code: Select all
$counter=mysql_num_rows($data);
$random=mt_rand(0,$counter-1);
$exclude=explode(';',$_SESSION['numbers']);
$sizeof_exclude=count($exclude);
if($sizeof_exclude<=$counter-1)
{
while(in_array($random,$exclude))
{
$random=mt_rand(0,counter-1);
}
}
else
{
session_unset();
//restart function
}
echo $random;
$_SESSION['numbers']=$_SESSION['numbers'].$random.';';EXPLANATION: I count the rows of a mysql query and i store it in a counter($counter) , next i create a random number between 0 and $counter-1 and i store it($random). Next using the global $_SESSION i get the numbers that already have been produced and store them in an $exclude array. Next i count the size of the exclude array($sizeof_exclude). Next i use the "if" so i can decide if all the numbers are produced so if NOT i proceed to produce a new one random number, using this logic i get "stuck" on a while loop creating random numbers until a the new random numbers NOT exist in the exclude array. Thats it.
The problem with that algorithm is: If the $counter is a big number at some time the while loop it will looping for a long time until it finds the new unique random number, for example if $counter=1000 and i have already produce 999 unique random numbers and i am looking for the 1000th unique random number (for example is 26) so the loop practically it will loop forever(theoretically sometime will find the 26).
Any other ideas?????