概率计算 发表于 2019-01-11 算法一 12345678910111213141516171819/** * 全概率计算 * * @param array $p array('a'=>0.5,'b'=>0.2,'c'=>0.4) * @return string 返回上面数组的key */function random($ps){ static $arr = array(); $key = md5(serialize($ps)); if (!isset($arr[$key])) { $max = array_sum($ps); foreach ($ps as $k=>$v) { $v = $v / $max * 10000; for ($i=0; $i<$v; $i++) $arr[$key][] = $k; } } return $arr[$key][mt_rand(0,count($arr[$key])-1)];} 算法二 12345678910111213141516171819202122232425/** * 根据权重概率获取 * @param $weights [ { k => weight } ] * @return int|string */public function getRand( $weights ){ $result = ''; $weightSum = array_sum( $weights ); foreach( $weights as $key => $weight ) { $randNum = mt_rand( 1, $weightSum ); if( $randNum <= $weight ) { $result = $key; break; } $weightSum -= $weight; } return $result;}