|  | Posted by Chung Leong on 07/17/06 23:22 
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.
  Navigation: [Reply to this message] |