Forum Moderators: coopster
i have a table where i store URLs with their ration to appear e.g
example1.com (50%)
example2.com (30%)
example3.com (50%)
example4.com (40%)
Now I want to make a code which can select randomly the URLs based on the intensity/ratio/trend value of it. for example in above sample data the example1.com has biggest trend to be selected randomly, example2.com has the lowest trend value so it should appear the least in random selections. it is done on many PPC systems.
thank you
$pick=rand(0,170); Finally, add up the row weights cumulatively until you go past $pick... (e.g. $pic = 70)
start .......... = 0
example1.com +50%=50
example2.com +30%=80 << stop here, 80>70 = example2.com
example3.com +50%=130
example4.com +40%=170
$runTot = 0;
$ret = array();
$i=0;
while($row = mysql_fetch_assoc($result)){
$ret[$i]["min"] = $runTot;
$ret[$i]["site"] = $row["site"];
$runTot += $row["ration"];
$i++;
}
$pick = random(0, $runTot);
for($i=count($ret); $i>0; $i--){
if($ret[$i]["min"] < $pick){
echo $ret[$i]["site"];
exit;
}
}
This is really crude i know and i havent tested it, but you see where i am going with it.
Ally
[edited by: Scally_Ally at 1:27 pm (utc) on July 2, 2008]
This algorithm is a bit more efficient then most ways to do random selections from an array with weight because it doesn't rely on creating an auxillary array with a position of each of the weights. Its elegant and simple.
You only have to turn the weights into a percentage of the total weight, and then pass the array into the following function:
*function w_rand($weights) {
* $r = mt_rand(1,1000);
* $offset = 0;
* foreach ($weights as $k => $w) {
** $offset += $w*1000;
** if ($r <= $offset) return $k;
* }
*}
Hope this helps someone.
_greg
PM me for a link to the article if you want.