Random weighted selection of an event [duplicate]

2019-02-15 11:39发布

Possible Duplicate:
Generating random results by weight in PHP?

i have made a database in which i store the name and the link of rss feeds.i have made the rss reader and everything is ok till now.I want to make a news scroller which will show the articles of the feeds.But i want to give to the feeds some weight values in order every feed to be selected according to its importance for me and automatically when a feed is selected from those in the database its articles only will be showed in the scroller.Any ideas of how can i do that???Thanks in advance..

p.s. my problem is how can i do aytomatically the random weighted choice of the feeds from the database and not how to show the articles of the feeds(i have done this part).

2条回答
劫难
2楼-- · 2019-02-15 12:09

You can find fast algorithm implemented and described - weighted random (in javascript but can be rewritten to PHP in a few minutes I think). It is much faster than loop through the array.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-02-15 12:25

Two ways to do this, that I can think of from the top of my head:

Option 1: Fill a new array with the key values from the set of data, where the weight determines how often an item is repeated. The proportion in this array then matches the weighted distribution. Simply grab using $arr[array_rand($arr)]. While simple and easy to understand, this will explode in your face if there are a LOT of items, or if the weight values are really high.

$weighted = array();
foreach($items as $item) {
    array_merge($weighted, array_fill(0, $item['weight'], $item['value']);
}
$result = $weighted[array_rand($weighted)];

Option 2. Sum the weights. Pick a random number between 0 and sum-of-weights. Loop over the elements in the dataset, compare against the random number you picked. As soon as you hit one that is equal to or bigger then the random index, select that element.

function findRandomWeighted(array $input) {
   $weight = 0;
   // I'm assuming you can get the weight from MySQL as well, so this loop really should not be required. In that case $weight becomes a parameter.
   foreach($items as $item) {
      $weight += $item['weight'];
   }

   $index = rand(1, $weight);
   foreach($items as $item) {
      $index -= $item['weight'];
      if($index <= 0) { return $item['value'] }
   }

   return null;
}

Following our conversation in the comments below, here is a Pastebin with the code in it:

http://pastebin.com/bLbhThhj

查看更多
登录 后发表回答