Re: Random With Odds

From: Date: Mon, 03 Jul 2000 23:29:05 +0000
Subject: Re: Random With Odds
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-4602@lists.php.net to get a copy of this message
on 7/3/00 3:53 PM, Nick Catalano at nick4753@nozone.net wrote: > I am about to create a BIG script that will allow a banner to rotate.. I > want to allow the user to select a weight for each banner.. 1 showing up > 1.5x as much as 2, 2 showing up 1.5x more than 3, 3 showing up 1.5x more > than 4, etc... how would I do that?? is there a way to setup rand to take in > account the odds of picking one number, and is it possible to change those > odds?? Sure... obviously, you need to make sure that you seed the random number generator each time you do this. Of course it will *vastly* simplify things if you have a 'baseline'. I.e. the banner with the lowest number of hits is 'x'. Say x = 100 banner1 => x = 100 banner2 => 1.5 * x = 150 banner3 => 2.0 * x = 200 <? $banner[0] = 100; $banner[1] = 150; $banner[2] = 200; //add up all the weights to get the total 'range' of values. for ($i = 0, $fullrange = 0 ; $i < sizeof($banner); $i++) { $fullrange += $banner[$i]; } $lottery = rand(0,$fullrange); // get a rand number inside the range. for ($i = 0, $lowerlimit = 0; $i < sizeof($banner); $i++) { //if we are in this banner's weight range if ($lottery < ($banner[$i] + $lowerlimit)) { echo "display banner $i"; break; } else { $lowerlimit += $banner[$i]; } } ?> This is just one algorithm to get this. I would actually use the recording infrormation about what banners have already been shown, rather than do a pure 'random' based on weights. This would enable you to take into account quotas (or being over, rather), etc. -k

« previous php.general (#4602) next »