/**
* 抽奖算法,
* @param array $data
* $array = [
* 'a' => 1,
* 'b' => 1,
* 'c' => 2,
* 'd' => 4,
* 'e' => 3,
* ];
* @return mixed
*/
function lottery(array $data)
{
$total = array_sum($data);
$seed = $total
$range = range(1, $total);
$output = [];
foreach ($data as $product => $pr) {
$total = array_sum($data);
$elementLength = $pr / $total * $seed;
for ($i = 0; $i < $elementLength; $i++) {
$output[array_pop($range)] = $product;
}
}
$r = array_rand($output);
return $output[$r];
}
PHP概率抽奖算法(空间换时间)
最新推荐文章于 2021-03-09 19:09:22 发布