2.15 Weighting Random Numbers


2.15 Weighting Random Numbers

You want to generate biased random numbers; an example might be an ad rotation system in which different users will not get the same number of page views.

Technique

PHP does not have built-in support for this, so we'll just have to roll our own:

 <?php // // Company -> Weight // $ads = array("Spacely Sprockets" => 1,              "The Rock Quarry" => 1,              "Springfield Power Plant" => 3,              "Microsoft"  => 10,              "Phillip Morris" => 5); $j = 0; foreach ($ads as $company => $weight) {     for ($i=0; $i < $weight; $i++) {         $dist[$j++] = $company; } srand((double)microtime()*1000000); $rand_num = mt_rand(0, $j - 1); shuffle($dist); // randomize the array, see chapter 4 for more details $company = $dist[$rand_num]; print "The Selected company was: $company"; ?> 

Comments

The previous script takes an array of companies and their respective weights, or how often they should be displayed in relation to each other. For example, Microsoft has a weight of 10, which means that it will be displayed more often than Springfield Power Plant that has a weight of 3.

We then initialize a foreach loop and loop through the $ads array. For each element of the $ads array, we put it into a new array for the amount of times specified by weight. For example, Microsoft has ten entries in the $dist array.

Finally, we seed the random number generator, pick out a random number that is the bounds of the array, and use that random number ( $rand_num ) as the index for the $dist array.

The example is only one method of generating a biased random number; for different methods , you should take a look at your statistics textbook .



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net