zoukankan      html  css  js  c++  java
  • php生成红包

    <?php
        /**
         * 随机生成红包金额
         * @param $n 红包个数
         * @param $sum  总金额 整数
         * @param $index_max  最大金额在数组中索引
         * @param $error
         * @return array|false
         */
        public static function GenRandRePacketsData($n,$sum,&$index_max,&$error)
        {
            if($sum < $n)
            {
                $error = '金额总数不能小于红包个数'; //金额总数必须大于红包个数;
                return false;
            }
            if($n > 50)
            {
                $error = '红包数量不能大于50';
                return false;
            }
            //$sum = $sum * 100;//转为分
            $rst = [];
            $ave = intval($sum/$n);  // 金额除去红包个数 平均值
            $one_rst = rand(1,$ave); // 随机取1到平均值的数
            $subSum = $one_rst;  
            $rst[] = $one_rst; 
            $index_min = 0;
            $index_max = 0;
            $min = $one_rst; 
            $max = $one_rst; 
    
            for($i = 2; $i <= $n; $i ++)
            {                   
                $ave = intval(($sum - $subSum)/($n - $i + 1)); 
                $one_rst = rand(1,$ave); 
                if($min > $one_rst) 
                {
                    $min = $one_rst;
                    $index_min = $i -1;
                }
                if($max < $one_rst) 
                {
                    $max = $one_rst;
                    $index_max = $i -1;
                }
                $rst[] = $one_rst;
                $subSum += $one_rst; 
            }
            $left = $sum - $subSum;
    
            if($left > 0)
            {
                $rst[$index_min] = ($rst[$index_min] + $left);
                if($rst[$index_min] > $max)
                {
                    $max = $rst[$index_min];
                    $index_max = $index_min;
                }
            }
            //检测重复的最大值处理,确保最大值唯一
            /*for($i =0; $i < $n; $i++)
            {
                if($rst[$i] === $max && $i !== $index_max)
                {
                    $one_rst = $rst[$i] -1;
                    $rst[$i] = $one_rst;
                    $rst[$index_max] = $max + 1;
                    break;
                }
            }*/
    
            //重新乱序
            shuffle($rst);
            //查找最大值
            $index_max = 0;
            $max = $rst[0];
            for($i =1; $i < $n; $i ++)
            {
                if($rst[$i]> $max)
                {
                    $index_max = $i;
                    $max = $rst[$i];
                }
            }
            return $rst;
        }
    

      

  • 相关阅读:
    Vue之利用vueRouter的元信息实现页面的缓存
    Vue之directives所遇小bug
    《CSS世界》读书笔记
    git 错误error: failed to push some refs to
    v-text指令消除刷新慢显示替换的过程
    防抖案例实战之仿百度搜索框即时搜索
    数字金额转大写金额
    常见前端安全
    sendmail邮箱部署设置
    Shell之监控cpu、内存、磁盘脚本
  • 原文地址:https://www.cnblogs.com/diguaer/p/6051151.html
Copyright © 2011-2022 走看看