zoukankan      html  css  js  c++  java
  • 抽奖权重计算

            header('Content-type:text/html;charset=utf-8');
        $data=array(
        0=>array('id'=>1,'name'=>'一等奖','weight'=>'5'),
        1=>array('id'=>2,'name'=>'二等奖','weight'=>'10'),
        2=>array('id'=>3,'name'=>'三等奖','weight'=>'25'),
        3=>array('id'=>4,'name'=>'谢谢抽奖','weight'=>'60')
        );
    
    
        // 权重数值越高,被返回的概率越大
        function countWeight($data){
            $weight=0;
            $temp=array();
            foreach($data as $v){
                $weight+=$v['weight'];
                for($i=0;$i<$v['weight'];$i++){
                    $temp[]=$v;//放大数组
                }
            }
            $int=mt_rand(0,$weight-1);//获取一个随机数
            $result=$temp[$int];
            return $result;
        }            

    测试

    $id0 = 0;
        $id1 = 0;
        $id2 = 0;
        $id3 = 0;
        for($i=1;$i<=100;$i++){
            $r = countWeight($data);
            switch($r['id']){
                case 1:
                    $id0++;
                    break;
                case 2:
                    $id1++;
                    break;
                case 3:
                    $id2++;
                    break;
                case 4:
                    $id3++;
                    break;
            }
        }
    
    
        d($r);
        d($id0);
        d($id1);
        d($id2);
        d($id3);
        
        
        //打印数组
        function d($data , $isexit = 0){
            echo '<pre>';
            var_dump($data);
            echo '</pre>';
            if ($isexit) exit();
        }
  • 相关阅读:
    tomcat部署https
    Java程序内存的简单分析
    接口设计原则
    英语常用口语
    洛谷 P3956 棋盘
    洛谷 P1101 单词方阵
    二分查找模板(准确找定值)
    洛谷 P1892 [BOI2003]团伙
    浅谈二分的边界问题
    deque简单解析
  • 原文地址:https://www.cnblogs.com/phpfensi/p/4448209.html
Copyright © 2011-2022 走看看