Re: Random Number Excluding Specified Value in Array
- From: "Rik" <luiheidsgoeroe@xxxxxxxxxxx>
- Date: Mon, 17 Jul 2006 22:25:29 +0200
Andy Hassall wrote:
On 17 Jul 2006 12:49:33 -0700, "AP"
<megacrosstab@xxxxxxxxxxxxxxxxxxxx> 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
.
- Follow-Ups:
- Re: Random Number Excluding Specified Value in Array
- From: Chung Leong
- Re: Random Number Excluding Specified Value in Array
- References:
- Random Number Excluding Specified Value in Array
- From: AP
- Re: Random Number Excluding Specified Value in Array
- From: Andy Hassall
- Random Number Excluding Specified Value in Array
- Prev by Date: Re: Random Number Excluding Specified Value in Array
- Next by Date: Re: multidimensional array declaration in php
- Previous by thread: Re: Random Number Excluding Specified Value in Array
- Next by thread: Re: Random Number Excluding Specified Value in Array
- Index(es):
Relevant Pages
|