Weighted Random Choice

Description: Random selection with a weighted bias.

<?PHP
 
// Give higher priorities to the users who pay the most.
// Gives lowest-priced rows the highest priority:
 
SELECT * FROM LINK ORDER BY RAND()*payPerClick/RAND();
 
 
// Gives highest-priced rows the highest priority
 
SELECT 'field' FROM 'table' WHERE 'ppc' > 0 ORDER BY RAND() / 'ppc' * RAND()
 
// Running the query above 6000 times produces:
// 3 cent: 402
// 4 cent: 517
// 5 cent: 615
// 7 cent: 800
// 9 cent: 1020
// 11 cent: 1214
// 13 cent: 1432
 
 
// OR
 
FUNCTION w_rand($weights) {
    $r = MT_RAND(1,1000);
    $offset = 0;
    FOREACH ($weights AS $k => $w) {
        $offset += $w*1000;
        IF ($r <= $offset) {
            RETURN $k;
        }
    }
}
 
?>

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.