You are here: Re: Random Number Excluding Specified Value in Array « PHP Programming Language « IT news, forums, messages
Re: Random Number Excluding Specified Value in Array

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]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация