“抽奖概率算法”的版本间的差异

来自代码库
跳转至: 导航搜索
 
第33行: 第33行:
 
         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),
第42行: 第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);