Domcsore Posted April 16, 2010 Share Posted April 16, 2010 Okay I've had so many ideas on how to do probability but when it comes to practice it's a little more difficult than I thought. Okay so what I am trying to create is a random advertisements script. So far I have this: public function adImage(){ $adimgLink[1] = 'template/template_files/ad_images/adhere.jpg'; $noAds = (count($adimgLink)); $randAd = rand(1,$noAds); echo '<img src="'.$adimgLink[$randAd].'" />'; } This works, however, I want it so customers can have a higher or lower probability of showing up depending on their budget they wish to spend on their advertisement. Any ideas? all help is appreciated =) Quote Link to comment https://forums.phpfreaks.com/topic/198705-probability/ Share on other sites More sharing options...
oni-kun Posted April 16, 2010 Share Posted April 16, 2010 You may want to use weighted results, For example: function weighted_random($values, $weights){ $count = count($values); $i = 0; $n = 0; $num = mt_rand(0, array_sum($weights)); while($i < $count){ $n += $weights[$i]; if($n >= $num){ break; } $i++; } return $values[$i]; } There are more algorithms of which are fairly simple to implement if need be, in this example you can use any positive integer as a weight (As an array). Quote Link to comment https://forums.phpfreaks.com/topic/198705-probability/#findComment-1042790 Share on other sites More sharing options...
Domcsore Posted April 16, 2010 Author Share Posted April 16, 2010 THANK YOU! Haha you have helped me so much, I did post this in the math section but had no reply so thank you for your quick response. Quote Link to comment https://forums.phpfreaks.com/topic/198705-probability/#findComment-1042791 Share on other sites More sharing options...
oni-kun Posted April 16, 2010 Share Posted April 16, 2010 THANK YOU! Haha you have helped me so much, I did post this in the math section but had no reply so thank you for your quick response. You're welcome. Quote Link to comment https://forums.phpfreaks.com/topic/198705-probability/#findComment-1042793 Share on other sites More sharing options...
l0ve2hat3 Posted April 16, 2010 Share Posted April 16, 2010 I like oni-kun's function but here's another idea <?php function adImage(){ $adimgLink[0] = 'template/template_files/ad_images/adhere.jpg'; $probability[0]=20; $adimgLink[1] = 'template/template_files/ad_images/adhere1.jpg'; $probability[1]=80; for($i=0;$i<count($adimgLink);$i++){ for($b=0;$b<$probability[$i];$b++)$ads[]=$adimgLink[$i]; } $noAds = (count($ads)-1); $randAd = rand(0,$noAds); echo '<img src="'.$ads[$randAd].'" />'; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/198705-probability/#findComment-1042796 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.