Random Number Excluding Specified Value in Array

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
Hello
Any suggestions on the most efficient way to generate a random number
from a range that will not return values specified in an array?

Re: Random Number Excluding Specified Value in Array

Depends how many values you have in the array compared with the overall range
of random numbers. If the number of values is small and the random value range
large, a simple "try-check array-retry as necessary" loop is likely to be the
most practical approach - although it'll degrade in performance as the
proportions of the two change and a significant percentage of the range is
marked as "used".

--
Andy Hassall :: andy@andyh.co.uk :: http://www.andyh.co.uk
http://www.andyhsoftware.co.uk/space :: disk and FTP usage analysis tool

Re: Random Number Excluding Specified Value in Array

Andy Hassall wrote:

Hmmz, you've got a point.
If the second case:
function get_rand_except(\$start,\$end,\$not){
if(!is_array(\$not) || empty(\$not)) return mt_rand(\$start,\$end); //we
don't bother when \$not is empty....
\$values = range(\$start,\$end); //numbers in range
\$choosable = array_diff(\$values,\$not); //remove unwanted numbers
if(count(\$choosable)==0) return false; //check wether we can choose
anything
\$choosable = array_value(\$choosable): //to reset array keys
return \$choosable[mt_rand(0,count(\$choosable)-1]; //return by random key
}

Grtz,
--
Rik Wasmus

Re: Random Number Excluding Specified Value in Array

Rik wrote:

That's rather expensive. There is really no need to remap every number
within the range. You only need to remap the holes. Say you want a
random number from 1 to 100, excluding 34, 62, and 87. What we can do
is map 34 to 100, 62 to 99, 87 to 98 with a hash table. Then we get a
random number from 1 to 97 and check the hash for a replacement value.

Re: Random Number Excluding Specified Value in Array

AP wrote:

Euhm, I am not really sure what you mean. Like this?

For integers:
function
rand_number_without_certain_values_for_some_reason(\$start,\$end,\$not){
\$i = 0;
do{
\$i++;
if(\$i > 5000) return false;
\$int = mt_renc(\$start,\$end);
} while (is_array(\$not) && in_array(\$int,\$not));
return \$int;
}

Had to build in safety (the \$i) to avoid endless looping when using
something like (1,4,array(range(1,4)))

Grtz,
--
Rik Wasmus

Re: Random Number Excluding Specified Value in Array

AP wrote:

No doubt better methods but a quick thought

\$fulllist = range(1, 12);
shuffle(\$fulllist);
\$vetolist = array (2,3,7,8);

\$alive = array_diff(\$fulllist, \$vetolist);

foreach (\$alive as \$value) {
echo "\$value, ";
}

Louise