开发者

Algorithm to select 1 of 2 Items Based on Probability

I'm coding a project that generates two arrays containing data. One array contains data for a specific country and the other contains data for all countries.

For example, if a user from the US makes a request, we will generate two arrays with data. One with data only for the US and the other with data for worldwide, including the US. I want to give the US array a 60% chance of being selected if the visitor is from the US. That means the other arra开发者_运维问答y will have a 40% chance of being selected.

How does one code this??


if(rand(1, 100) <= $probability_for_first_array)
{
    use_the($first_array);
}
else
{
    use_the($second_array);
}

I find this a straightforward, easy to read solution


<?php

$us_data = "us";
$worldwide_data = "worldwide";

$probabilities = array($us_data => 0.60, $worldwide_data => 0.40);

/* Code courtesy of Jesse Farmer
 * For more details see http://goo.gl/fzq5
 */
function get_data($prob)
{
 $random = mt_rand(0, 1000);
 $offset = 0;
 foreach ($prob as $key => $probability)
 {
  $offset += $probability * 1000;
  if ($random <= $offset)
  {
   return $key;
  }
 }
}

?>

Gabi's example is fine for two sets, but if you have more data sets to pick from, the if-else structure is not appropriate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜