• 最近做抽奖的活动


    1.抽奖算法简化如下:

    function choujiang($config)
    {
        $isOk = 0;
        foreach ($config['Win'] as $key => $value) {
            if ($value['upperLimit'] > $value['existing']) {
                $isOk = 1;
            }
        }
        if ($isOk === 0) return "所有商品都被中完了";
    
        $mt_rand = mt_rand(0, 9999); // mt_rand比rand效率要高4倍
        if ($mt_rand < $config['NoWin']['probability']) {
            return '对不起,你没有中奖';
        } else {
            $sum = array_sum(array_column($config['Win'], 'probability'));
            if ($sum !== 10000) return '概率和不等于10000';
            return gailv($config['Win']);
        }
    }
    
    function gailv($config)
    {
        $mt_rand = mt_rand(0, 9999);
        $begin = 0;
        foreach ($config as $key => $value) {
            if ($mt_rand >= $begin && $mt_rand < $begin + $value['probability']) {
                if ($value['upperLimit'] <= $value['existing']) {
                    return gailv($config);
                } else {
                    return "恭喜您中奖了,商品id:{$value['product_id']},商品名:{$value['product_name']}";
                }
            }
            $begin += $value['probability'];
        }
    }
    
    /*
        不中奖概率:80.00%
        中奖概率:20.00%,其中:中product1的概率:10.00%, 此种奖品数:500个,已经中了200个
    */
    
    $config = [
        'NoWin' => ['probability' => 8000],
        'Win' => [
            ['product_id' => 1, 'product_name' => 'product1', 'probability' => 1000, 'upperLimit' => 500, 'existing' => 200],
            ['product_id' => 2, 'product_name' => 'product2', 'probability' => 2000, 'upperLimit' => 500, 'existing' => 500],
            ['product_id' => 3, 'product_name' => 'product3', 'probability' => 3000, 'upperLimit' => 500, 'existing' => 200],
            ['product_id' => 4, 'product_name' => 'product4', 'probability' => 4000, 'upperLimit' => 500, 'existing' => 200],
        ]
    ];
    
    echo choujiang($config);
    
    
  • 相关阅读:
    记忆化搜索 E
    网络流 O
    线段树 B数据结构 牛客练习赛28
    N
    线段树 G
    K
    F
    补一下昨天的博客 J
    selenium-1-python
    selenium入门知识
  • 原文地址:https://www.cnblogs.com/wangweiwen/p/6217221.html
Copyright © 2020-2023  润新知