“抽奖概率算法”的版本间的差异
来自代码库
(创建页面,内容为“ →* * @desc 抽奖概率算法 - 生成品类 * @author * @date: private function lotteryWeight($data) { if(!$data...”) |
|||
(未显示同一用户的1个中间版本) | |||
第10行: | 第10行: | ||
return false; | return false; | ||
} | } | ||
− | |||
$item = []; | $item = []; | ||
$code = ''; | $code = ''; | ||
第17行: | 第16行: | ||
$item[$v['id']] = $v['weight']; | $item[$v['id']] = $v['weight']; | ||
} | } | ||
− | |||
//中奖概率基数 | //中奖概率基数 | ||
$num = array_sum($item); | $num = array_sum($item); | ||
− | |||
foreach($item as $k => $v){ | foreach($item as $k => $v){ | ||
//获取一个1到当前基数范围的随机数 阶段性权重值 | //获取一个1到当前基数范围的随机数 阶段性权重值 | ||
第31行: | 第28行: | ||
} | } | ||
} | } | ||
− | |||
if(!$code){ | if(!$code){ | ||
return false; | return false; | ||
} | } | ||
− | |||
return $code; | return $code; | ||
} | } | ||
− | + | $data = array( | |
− | + | ||
− | $data = array( | + | |
array('id'=>1,'name'=>'一等奖','weight'=>1), | array('id'=>1,'name'=>'一等奖','weight'=>1), | ||
array('id'=>2,'name'=>'二等奖','weight'=>4), | array('id'=>2,'name'=>'二等奖','weight'=>4), | ||
第47行: | 第40行: | ||
array('id'=>5,'name'=>'没中奖','weight'=>50) | array('id'=>5,'name'=>'没中奖','weight'=>50) | ||
); | ); | ||
− | |||
//抽取奖品 | //抽取奖品 | ||
$code = $this->lotteryWeight($data); | $code = $this->lotteryWeight($data); |
2017年5月5日 (五) 08:37的最新版本
/** * @desc 抽奖概率算法 - 生成品类 * @author * @date */ private function lotteryWeight($data) { if(!$data || !count($data)){ return false; } $item = []; $code = ; //每个奖品的中奖几率,奖品ID作为数组下标 foreach($data as $k => $v){ $item[$v['id']] = $v['weight']; } //中奖概率基数 $num = array_sum($item); foreach($item as $k => $v){ //获取一个1到当前基数范围的随机数 阶段性权重值 $rand = mt_rand(1,$num); if($rand <= $v){ //dump($rand .'-------'.$v); $code = $k; break; }else{ $num -= $v; //末等奖必中 } } if(!$code){ return false; } return $code; } $data = array( array('id'=>1,'name'=>'一等奖','weight'=>1), array('id'=>2,'name'=>'二等奖','weight'=>4), array('id'=>3,'name'=>'三等奖','weight'=>15), array('id'=>4,'name'=>'四等奖','weight'=>30), array('id'=>5,'name'=>'没中奖','weight'=>50) ); //抽取奖品 $code = $this->lotteryWeight($data);