Click to See Complete Forum and Search --> : Weighted Random


Pezmc
01-17-2007, 01:54 PM
I have a mysql query querying my database using order by RAND() LIMIT 1 to sellect a random coice from the database, however I would like to have the chance of a object being chosen increased for certain values (Weighting?)

In my database I have:

id name weight
1 Pezm 1
2 Shog 1.1
3 Ebay 1.2
4 PLp 1.3
5 php 1.4


So follwing the information in my database if a weighted random script is used php shuld be the most frequent with 1.4*the chance to get chosen, compared to Pezm,

How can this be acchieved?

NightShift58
01-17-2007, 02:15 PM
Not in conjunction with RAND().

NightShift58
01-17-2007, 03:11 PM
This isn't the direct answer to your direct question, but it does give a weighted result.<?php
include "DBconnect2.inc.php";

$sql = "SELECT * from `weighted`";
$qry = mysql_query($sql) or die("SQL Error: $sql<br>" . mysql_error());

$total = 0;
$arrWEIGHT = array();
while ($row = mysql_fetch_assoc($qry)) :
print $row['name'] . ": " . $row['weight'] . "<br>";
$arrWEIGHT[$row['id']] = round($row['weight'],2);
$total += $row['weight'];
endwhile;
print $total;

$arrWEIGHT2 = array();
foreach($arrWEIGHT as $key => $val) :
$thisLOOP = intval($val / $total * 100);
for ($x = 0; $x < $thisLOOP; $x++) :
$arrWEIGHT2[] = $key;
endfor;
endforeach;

//shuffle($arrWEIGHT2);

$arrCOUNT = array();
FOR ($x = 0; $x < 1000; $x++) :
$rand_key = rand(0, count($arrWEIGHT2)-1);
$arrCOUNT[$arrWEIGHT2[$rand_key]]++;
//print "<br>$x : " . $arrWEIGHT2[$rand_key];
ENDFOR;

ksort($arrCOUNT);

print "<pre>";
print_r($arrCOUNT);
print "</pre>";

?>

digdan
04-29-2010, 11:35 PM
I have made several small weighted random scripts in php, here is an example :

function wrandom($array) {
foreach($array as $k=>$v) $max += $v;
$roll = rand(0,$max);
foreach($array as $k=>$v) if ($roll <= ($rcount += $v)) return $k;
return $k;
}

More information at my personal blog www.danmorgan.net (htpp://www.danmorgan.net)