Random weighted selection of an event [duplicate]

拟墨画扇 提交于 2019-11-30 19:32:59

问题


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).


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/4623036/random-weighted-selection-of-an-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!