Advertisement
Guest User

Sander Bol

a guest
Jan 10th, 2011
514
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.60 KB | None | 0 0
  1. <?php
  2. // First some SQL to execute
  3. // You will only need the ALTER and UPDATE, the insert is to generate some example data so we can actually run tests on it.
  4. /**
  5. ALTER TABLE `test`.`feeds` ADD COLUMN `weight` SMALLINT NOT NULL DEFAULT 1  AFTER `url`;
  6. INSERT INTO `feeds` (name, url)
  7. VALUES
  8. ('Test 1', 'http://www.google.com/feeds'),
  9. ('Test 2', 'http://some-url.com'),
  10. ('Test 3', 'http://feeds-r-us.com'),
  11. ('Test 4', 'http://even-more-links.com'),
  12. ('Test 5', 'http://www.veryimportantfeed.com');
  13. UPDATE `test`.`feeds` SET `weight`=1 WHERE `id`='1'
  14. UPDATE `test`.`feeds` SET `weight`=1 WHERE `id`='2'
  15. UPDATE `test`.`feeds` SET `weight`=1 WHERE `id`='3'
  16. UPDATE `test`.`feeds` SET `weight`=1 WHERE `id`='4'
  17. UPDATE `test`.`feeds` SET `weight`=6 WHERE `id`='5'
  18. **/
  19.  
  20. function findRandomWeighted(array $items) {
  21.    $maxWeight = 0;
  22.    // Sum all the weights.
  23.    foreach($items as $item) {
  24.         $maxWeight += $item['weight'];
  25.    }
  26.    
  27.    $index = rand(1, $maxWeight);
  28.    foreach($items as $item) {
  29.        $index -= $item['weight'];
  30.        if($index <= 0) {
  31.             return $item;
  32.        }
  33.    }
  34. }
  35.  
  36. $conn = mysql_connect('localhost','username','password');
  37. mysql_select_db('test', $conn);
  38.  
  39. $query = "SELECT * FROM `feeds`";
  40.  
  41. $result = mysql_query($query);
  42. $data   = array();
  43. while($output = mysql_fetch_assoc($result)) {
  44.     $data[] = $output;
  45. }
  46.  
  47. // Test
  48. $selections = array(1=>0, 2=>0, 3=>0, 4=>0, 5=>0);
  49. for($i = 0; $i < 1000; $i++) {
  50.     $feed = findRandomWeighted($data);
  51.     $selections[$feed['id']]++;
  52. }
  53.  
  54. // Result should be approximately equal to the distribution of the weight.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement