Forums
This topic is locked
HELP unique random number
01 May 2007 12:27:16 sue grice posted:
Hi, I have been pulling my hair out yesterday and today trying to figure out why this little bit of code wont give me a unique random number. can anyone enlighten me PLEASE <img src=../images/dmxzone/forum/icon_smile_sad.gif border=0 align=middle> numbers is an array to store the unique random numbers (kind of like lottery numbers). it all works OK (except for not giving unique numbers) I think the while loop is the problem, but not sure why??????
for ($i=0 ; $i<11; $i++)
{
$rand = rand(0,10);
for( $y = 0 ; $y <11; $y++){
while ($rand == $numbers[$y])
{
$rand = rand(0,10);
}
}
$numbers[$i] = $rand;
}
thank you very much in advance
sue
Replies
Replied 23 May 2007 16:56:46
23 May 2007 16:56:46 Andrew Peace replied:
sue--
Simple logic mistake. Your while loop needs to be on the outside of the foor loop. Think of it this way:
WHILE the number is still not unique:
FOR each number:
check if it matches that number
Like so:
<pre id=code><font face=courier size=2 id=code>
for ($i=0;$i<11;$i++ ){
$done=false;
while(!$done){
$rand=rand(0,10);
$done=true;
for($y=0;$y<count($numbers);$y++ ){
if($rand==$numbers[$y])
$done=false;
}
}
$numbers[$i] = $rand;
}
</font id=code></pre id=code>
Demo page here: http://www.andrewpeace.com/unique-random-numbers.php
Andrew Peace - Like my posts? You'll love my site
Simple logic mistake. Your while loop needs to be on the outside of the foor loop. Think of it this way:
WHILE the number is still not unique:
FOR each number:
check if it matches that number
Like so:
<pre id=code><font face=courier size=2 id=code>
for ($i=0;$i<11;$i++ ){
$done=false;
while(!$done){
$rand=rand(0,10);
$done=true;
for($y=0;$y<count($numbers);$y++ ){
if($rand==$numbers[$y])
$done=false;
}
}
$numbers[$i] = $rand;
}
</font id=code></pre id=code>
Demo page here: http://www.andrewpeace.com/unique-random-numbers.php
Andrew Peace - Like my posts? You'll love my site