donxbje866688 2018-04-16 12: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 12: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条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭