Re: Random Number Excluding Specified Value in Array
- From: "Chung Leong" <chernyshevsky@xxxxxxxxxxx>
- Date: 17 Jul 2006 16:22:27 -0700
Rik 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
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.
.
- References:
- Random Number Excluding Specified Value in Array
- From: AP
- Re: Random Number Excluding Specified Value in Array
- From: Andy Hassall
- Re: Random Number Excluding Specified Value in Array
- From: Rik
- Random Number Excluding Specified Value in Array
- Prev by Date: Re: php installation prolem
- Next by Date: Hi.. About PHP & Javascript Develop Environment
- Previous by thread: Re: Random Number Excluding Specified Value in Array
- Next by thread: Re: Random Number Excluding Specified Value in Array
- Index(es):