Rand(); with exclusion to and already randomly generated number..?
Posted
by Stefan
on Stack Overflow
See other posts from Stack Overflow
or by Stefan
Published on 2010-05-12T17:37:56Z
Indexed on
2010/05/12
17:44 UTC
Read the original article
Hit count: 243
Hey, I have a function which calls a users associated users from a table. The function then uses the rand(); function to chose from the array 5 randomly selected userID's however!...
In the case where a user doesnt have many associated users but above the min (if below the 5 it just returns the array as it is) then it gives bad results due to repeat rand numbers...
How can overcome this or exclude a previously selected rand number from the next rand(); function call.
Here is the section of code doing the work. Bare in mind this must be highly efficient as this script is used everywhere.
$size = sizeof($users)-1;
$nusers[0] = $users[rand(0,$size)];
$nusers[1] = $users[rand(0,$size)];
$nusers[2] = $users[rand(0,$size)];
$nusers[3] = $users[rand(0,$size)];
$nusers[4] = $users[rand(0,$size)];
return $nusers;
Thanks in advance! Stefan
© Stack Overflow or respective owner