zoukankan      html  css  js  c++  java
  • PHP概率,抽奖

    随机数,游标卡尺。
    一个大饼,随机到哪个坑里,就中哪个奖。
    大转盘!
    公平公正!

    // 获取锦鲤
    public function getGoldPig() {
        $pig_gift_bag = [
            [
                'id' => 1,
                'name' => '小金猪',
                'weight' => 1000
            ],
            [
                'id' => 2,
                'name' => '中金猪',
                'weight' => 100
            ],
            [
                'id' => 3,
                'name' => '大金猪',
                'weight' => 10
            ],
            [
                'id' => 4,
                'name' => '超大金猪',
                'weight' => 1
            ],
            [
                'id' => 5,
                'name' => '抱歉,下次就中了',
                'weight' => 10000
            ],
        ];
    
        foreach ($pig_gift_bag as $key => $val) {
            $giftWeightArr[$val['id']] = $val['weight'];
        }
    
    
        for ($i=0;$i<10;$i++) {
            $gid = $this->getLuckyGift($giftWeightArr); //根据概率获取奖项id
            dump($pig_gift_bag[$gid-1]['name']);
        }
    
    }
    
    function getLuckyGift($giftWeightArr) {
        $result = '';
    
        //概率数组的总概率精度
        $sumWeight = array_sum($giftWeightArr); //计算数组中元素的和
        $luckyNum = mt_rand(1, $sumWeight);
        //概率数组循环
        $beginCursor = $endCursor = 0;
        foreach ($giftWeightArr as $gid => $weight) {
            $beginCursor = $endCursor;
            $endCursor += $weight;
    
            if ($luckyNum > $beginCursor && $luckyNum <= $endCursor) {
                $result = $gid;
                break;
            }
        }
        return $result;
    }
    
    string(24) "抱歉,下次就中了"
    string(24) "抱歉,下次就中了"
    string(24) "抱歉,下次就中了"
    string(24) "抱歉,下次就中了"
    string(24) "抱歉,下次就中了"
    string(24) "抱歉,下次就中了"
    string(24) "抱歉,下次就中了"
    string(9) "小金猪"
    string(24) "抱歉,下次就中了"
    string(9) "小金猪"
    

    有点意思哦!

  • 相关阅读:
    Mysql_常规操作
    三剑客
    Nginx_安全2
    shell_常规小脚本
    redis数据库持久化
    redis数据库操作
    keepalived高可用lvs集群
    ansible的roles角色
    keepalived高可用
    keepalived概念
  • 原文地址:https://www.cnblogs.com/jiqing9006/p/10289783.html
Copyright © 2011-2022 走看看