zoukankan      html  css  js  c++  java
  • 最近做抽奖的活动

    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);
    
    
  • 相关阅读:
    单例模式(Singleton)的6种实现
    深入浅出单实例Singleton设计模式
    Singleton单例模式
    面试中的Singleton
    海量数据存储之Key-Value存储简介
    大数据时代的 9 大Key-Value存储数据库
    python 多线程两种实现方式,Python多线程下的_strptime问题,
    pycURL的内存问题
    百万级访问网站前期的技术准备
    IPv6 tutorial – Part 6: Site-local addresses and link-local addresses
  • 原文地址:https://www.cnblogs.com/wangweiwen/p/6217221.html
Copyright © 2011-2022 走看看