Snippet Name: Weighted Random Choice
Description: Random selection with a weighted bias.
Also see: » Random Image from Directory
» Random banner picker
» Generate random string
» Rounded random numbers
» Random Pronounceable Passwords
» Pick Randomly from Array
Comment: (none)
Language: PHP
Highlight Mode: PHP
Last Modified: March 16th, 2009
|
<?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;
}
}
}
?> |