|
Posted by Rik on 07/17/06 20:25
Andy Hassall wrote:
> On 17 Jul 2006 12:49:33 -0700, "AP"
> <megacrosstab@greenixsolutions.com> wrote:
>
>> Any suggestions on the most efficient way to generate a random number
>> from a range that will not return values specified in an 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".
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
Navigation:
[Reply to this message]
|