donxbje866688 2018-04-16 04:32
浏览 370
已采纳

PHP以百分比折扣生成折扣代码

I'm working on making a shopping web site which created a unique discount code for each person.
I want to generate a one percent discount for this code, for example:

x3M2qE => 10%
gh2WW4 => 20%
...

These codes should be created in such a way that The probability of generating 90% is much less than the generation of 10%.

Identify the best and most optimal algorithm and help me to do it properly,
thanks.

  • 写回答

2条回答 默认 最新

  • dousi8237 2019-08-24 04:31
    关注

    Optimal Code:

    $chances = [
        '50%' => 60,
        '10%' => 30,
        '5%' => 5,
        '4%' => 2,
        '3%' => 1,
        '2%' => 1,
        '1%' => 1,
    ];
    
    $max_chance = 0;
    foreach($chances as $key => $val) {
        $max_chance += $val;
    }
    
    $rand = mt_rand(1, $max_chance);
    
    $cur = 0;
    foreach($chances as $key => $val) {
        $cur += $val;
        if($rand <= $cur)
            echo $key;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部