算法一

<?php 
$total=19.5;//红包总金额
$num=9;// 分成10个红包,支持10人随机领取
$min=0.01;//每个人最少能收到0.01元
$money_arr=array(); //存入随机红包金额结果
for ($i=1;$i<$num;$i++)
{
    $safe_total=($total-($num-$i)*$min)/($num-$i);//随机安全上限
    $money= mt_rand($min*100,$safe_total*100)/100;
    $total=$total-$money;
    $money_arr[]= $money;
    echo '第'.$i.'个红包:'.$money.' 元,余额:'.$total.' 元 '."<br/>";
}
echo '第'.$num.'个红包:'.round($total,2).' 元,余额:0 元';
$money_arr[] = round($total,2);

dd($money_arr);
来源:https://www.cnblogs.com/best-always/p/10469624.html
<?php

/*
 * Author:xx_lufei
 * Time:2016年9月14日09:55:36
 * Note:红包生成随机算法
 */

class Reward
{
    public $rewardMoney;        #红包金额、单位元
    public $rewardNum;          #红包数量

    #执行红包生成算法
    public function splitReward($rewardMoney, $rewardNum, $max, $min)
    {
        #传入红包金额和数量,因为小数在计算过程中会出现很大误差,所以我们直接把金额放大100倍,后面的计算全部用整数进行
        $min = $min * 100;
        $max = $max * 100;
        #预留出一部分钱作为误差补偿,保证每个红包至少有一个最小值
        $this->rewardMoney = $rewardMoney * 100 - $rewardNum * $min;
        $this->rewardNum = $rewardNum;
        #计算出发出红包的平均概率值、精确到小数4位。
        $avgRand = 1 / $this->rewardNum;
        $randArr = array();
        #定义生成的数据总合sum
        $sum = 0;
        $t_count = 0;
        while ($t_count < $rewardNum) {
            #随机产出四个区间的额度
            $c = rand(1, 100);
            if ($c < 15) {
                $t = round(sqrt(mt_rand(1, 1500)));
            } else if ($c < 65) {
                $t = round(sqrt(mt_rand(1500, 6500)));
            } else if ($c < 95) {
                $t = round(sqrt(mt_rand(6500, 9500)));
            } else {
                $t = round(sqrt(mt_rand(9500, 10000)));
            }
            ++$t_count;
            $sum += $t;
            $randArr[] = $t;
        }

        #计算当前生成的随机数的平均值,保留4位小数
        $randAll = round($sum / $rewardNum, 4);

        #为将生成的随机数的平均值变成我们要的1/N,计算一下每个随机数要除以的总基数mixrand。此处可以约等处理,产生的误差后边会找齐
        #总基数 = 均值/平均概率
        $mixrand = round($randAll / $avgRand, 4);

        #对每一个随机数进行处理,并乘以总金额数来得出这个红包的金额。
        $rewardArr = array();
        foreach ($randArr as $key => $randVal) {
            #单个红包所占比例randVal
            $randVal = round($randVal / $mixrand, 4);
            #算出单个红包金额
            $single = floor($this->rewardMoney * $randVal);
            #小于最小值直接给最小值
            if ($single < $min) {
                $single += $min;
            }
            #大于最大值直接给最大值
            if ($single > $max) {
                $single = $max;
            }
            #将红包放入结果数组
            $rewardArr[] = $single;
        }

        #对比红包总数的差异、将差值放在第一个红包上
        $rewardAll = array_sum($rewardArr);
        $rewardArr[0] = $rewardMoney * 100 - ($rewardAll - $rewardArr[0]);#此处应使用真正的总金额rewardMoney,$rewardArr[0]可能小于0

        #第一个红包小于0时,做修正
        if ($rewardArr[0] < 0) {
            rsort($rewardArr);
            $this->add($rewardArr, $min);
        }

        rsort($rewardArr);
        #随机生成的最大值大于指定最大值
        if ($rewardArr[0] > $max) {
            #差额
            $diff = 0;
            foreach ($rewardArr as $k => &$v) {
                if ($v > $max) {
                    $diff += $v - $max;
                    $v = $max;
                } else {
                    break;
                }
            }
            $transfer = round($diff / ($this->rewardNum - $k + 1));
            $this->diff($diff, $rewardArr, $max, $min, $transfer, $k);
        }
        return $rewardArr;
    }

    #处理所有超过最大值的红包
    public function diff($diff, &$rewardArr, $max, $min, $transfer, $k)
    {
        #将多余的钱均摊给小于最大值的红包
        for ($i = $k; $i < $this->rewardNum; $i++) {
            #造随机值
            if ($transfer > $min * 20) {
                $aa = rand($min, $min * 20);
                if ($i % 2) {
                    $transfer += $aa;
                } else {
                    $transfer -= $aa;
                }
            }
            if ($rewardArr[$i] + $transfer > $max) continue;
            if ($diff - $transfer < 0) {
                $rewardArr[$i] += $diff;
                $diff = 0;
                break;
            }
            $rewardArr[$i] += $transfer;
            $diff -= $transfer;
        }
        if ($diff > 0) {
            $i++;
            $this->diff($diff, $rewardArr, $max, $min, $transfer, $k);
        }
    }

    #第一个红包小于0,从大红包上往下减
    public function add(&$rewardArr, $min)
    {
        foreach ($rewardArr as &$re) {
            $dev = floor($re / $min);
            if ($dev > 2) {
                $transfer = $min * floor($dev / 2);
                $re -= $transfer;
                $rewardArr[$this->rewardNum - 1] += $transfer;
            } elseif ($dev == 2) {
                $re -= $min;
                $rewardArr[$this->rewardNum - 1] += $min;
            } else {
                break;
            }
        }
        if ($rewardArr[$this->rewardNum - 1] > $min || $rewardArr[$this->rewardNum - 1] == $min) {
            return;
        } else {
            $this->add($rewardArr, $min);
        }
    }
}

<?php 
class CreateReward{
    /*
     * 生成红包
     * author    xx     2016年9月23日13:53:38
     * @param   int          $total               红包总金额
     * @param   int          $num                 红包总数量
     * @param   int          $max                 红包最大值
     * 
     */
    public function random_red($total, $num, $max, $min)
    {
        #总共要发的红包金额,留出一个最大值;
        $total = $total - $max;
        $reward = new Reward();
        $result_merge = $reward->splitReward($total, $num, $max - 0.01, $min);
        sort($result_merge);
        $result_merge[1] = $result_merge[1] + $result_merge[0];
        $result_merge[0] = $max * 100;
        foreach ($result_merge as &$v) {
            $v = floor($v) / 100;
        }
        return $result_merge;
    }
}
来源:https://juejin.im/entry/5905bea55c497d00583d0f0d

算法三

<?php
/**
 * 随机红包+固定红包算法[策略模式]
 * copyright (c) 2016 http://blog.csdn.net/CleverCode
 */
 
//配置传输数据DTO
class OptionDTO
{/*{{{*/
 
    //红包总金额
    public $totalMoney;
 
    //红包数量
    public $num;
 
    //范围开始
    public $rangeStart;
 
    //范围结算
    public $rangeEnd;
 
    //生成红包策略
    public $builderStrategy;
 
    //随机红包剩余规则
    public $randFormatType; //Can_Left:不修数据,可以有剩余;No_Left:不能有剩余
 
    public static function create($totalMoney,$num,$rangeStart,$rangEnd,
        $builderStrategy,$randFormatType = 'No_Left')
    {/*{{{*/
        $self = new self();
        $self->num = $num;
        $self->rangeStart = $rangeStart;
        $self->rangeEnd = $rangEnd;
        $self->totalMoney = $totalMoney;
        $self->builderStrategy = $builderStrategy;
        $self->randFormatType = $randFormatType;
        return $self; 
    }/*}}}*/
 
}/*}}}*/
 
//红包生成器接口
interface IBuilderStrategy
{/*{{{*/
    //创建红包
    public function create();    
    //设置配置
    public function setOption(OptionDTO $option); 
    //是否可以生成红包
    public function isCanBuilder();
    //生成红包函数
    public function fx($x);
}/*}}}*/
 
//固定等额红包策略
class EqualPackageStrategy implements IBuilderStrategy
{/*{{{*/
    //单个红包金额
    public $oneMoney;
 
    //数量
    public $num;
 
    public function __construct($option = null) 
    {
        if($option instanceof OptionDTO)
        {
            $this->setOption($option);
        }
    }
 
    public function setOption(OptionDTO $option)
    {
        $this->oneMoney = $option->rangeStart;
        $this->num = $option->num;
    }
 
    public function create() 
    {/*{{{*/
 
        $data = array();
        if(false == $this->isCanBuilder())
        {
            return $data;    
        }
 
        $data = array();
        if(false == is_int($this->num) || $this->num <= 0) 
        {
            return $data;    
        }
        for($i = 1;$i <= $this->num;$i++)
        {
            $data[$i] = $this->fx($i);
        }
        return $data;
    }/*}}}*/
    
    /**
     * 等额红包的方程是一条直线 
     * 
     * @param mixed $x 
     * @access public
     * @return void
     */
    public function fx($x) 
    {/*{{{*/
        return $this->oneMoney; 
    }/*}}}*/
 
    /**
     * 是否能固定红包 
     * 
     * @access public
     * @return void
     */
    public function isCanBuilder()
    {/*{{{*/
        if(false == is_int($this->num) || $this->num <= 0) 
        {
            return false;    
        }
 
        if(false ==  is_numeric($this->oneMoney) || $this->oneMoney <= 0)
        {
            return false;
        }
 
        //单个红包小于1分
        if($this->oneMoney < 0.01)
        {
            return false;
        }
        
        return true;
 
    }/*}}}*/
 
 
}/*}}}*/
 
//随机红包策略(三角形)
class RandTrianglePackageStrategy implements IBuilderStrategy
{/*{{{*/
    //总额
    public $totalMoney;
 
    //红包数量
    public $num;
 
    //随机红包最小值
    public $minMoney;
 
    //随机红包最大值
    public $maxMoney;
 
    //修数据方式:NO_LEFT: 红包总额 = 预算总额;CAN_LEFT: 红包总额 <= 预算总额
    public $formatType; 
 
    //预算剩余金额
    public $leftMoney;
 
 
    public function __construct($option = null) 
    {/*{{{*/
        if($option instanceof OptionDTO)
        {
            $this->setOption($option);
        }
    }/*}}}*/
 
    public function setOption(OptionDTO $option)
    {/*{{{*/
        $this->totalMoney = $option->totalMoney;
        $this->num = $option->num;
        $this->formatType = $option->randFormatType;
        $this->minMoney = $option->rangeStart;
        $this->maxMoney = $option->rangeEnd;
        $this->leftMoney = $this->totalMoney;
    }/*}}}*/
 
    /**
     * 创建随机红包 
     * 
     * @access public
     * @return void
     */
    public function create() 
    {/*{{{*/
        
        $data = array();
        if(false == $this->isCanBuilder())
        {
            return $data;    
        }
        
        $leftMoney = $this->leftMoney;
        for($i = 1;$i <= $this->num;$i++)
        {
            $data[$i] = $this->fx($i);
            $leftMoney = $leftMoney - $data[$i]; 
        }
 
        //修数据
        list($okLeftMoney,$okData) = $this->format($leftMoney,$data);
 
        //随机排序
        shuffle($okData);
        $this->leftMoney = $okLeftMoney;
 
        return $okData;
    }/*}}}*/
 
    /**
     * 是否能够发随机红包 
     * 
     * @access public
     * @return void
     */
    public function isCanBuilder()
    {/*{{{*/
        if(false == is_int($this->num) || $this->num <= 0) 
        {
            return false;    
        }
 
        if(false ==  is_numeric($this->totalMoney) || $this->totalMoney <= 0)
        {
            return false;
        }
 
        //均值
        $avgMoney = $this->totalMoney / 1.0 / $this->num;
        
        //均值小于最小值
        if($avgMoney < $this->minMoney )
        {
            return false;
        }
        
        return true;
 
    }/*}}}*/
 
    /**
     * 获取剩余金额 
     * 
     * @access public
     * @return void
     */
    public function getLeftMoney()
    {/*{{{*/
        return $this->leftMoney;
    }/*}}}*/
 
    /**
     * 随机红包生成函数。三角函数。[(1,0.01),($num/2,$avgMoney),($num,0.01)] 
     * 
     * @param mixed $x,1 <= $x <= $this->num; 
     * @access public
     * @return void
     */
    public function fx($x)
    {/*{{{*/
        
        if(false == $this->isCanBuilder())
        {
            return 0;
        }
 
        if($x < 1 || $x > $this->num)
        {
            return 0;
        }
        
        $x1 = 1;
        $y1 = $this->minMoney;
        
        //我的峰值
        $y2 = $this->maxMoney;
 
        //中间点
        $x2 = ceil($this->num /  1.0 / 2);
 
        //最后点
        $x3 = $this->num;
        $y3 = $this->minMoney;  
 
        //当x1,x2,x3都是1的时候(竖线)
        if($x1 == $x2 && $x2 == $x3)
        {
            return $y2;
        }
 
        // '/_\'三角形状的线性方程
        //'/'部分
        if($x1 != $x2 && $x >= $x1 && $x <= $x2)
        {
 
            $y = 1.0 * ($x - $x1) / ($x2 - $x1) * ($y2 - $y1) + $y1;  
            return number_format($y, 2, '.', '');
        }
 
        //'\'形状
        if($x2 != $x3 && $x >= $x2 && $x <= $x3)
        {
 
            $y = 1.0 * ($x - $x2) / ($x3 - $x2) * ($y3 - $y2) + $y2;  
            return number_format($y, 2, '.', '');
        }
        
        return 0;
 
 
    }/*}}}*/
 
    /**
     * 格式化修红包数据 
     * 
     * @param mixed $leftMoney 
     * @param array $data 
     * @access public
     * @return void
     */
    private function format($leftMoney,array $data)
    {/*{{{*/
 
        //不能发随机红包
        if(false == $this->isCanBuilder())
        {
            return array($leftMoney,$data);  
        }
        
        //红包剩余是0
        if(0 == $leftMoney)
        {
            return array($leftMoney,$data);  
        }
 
        //数组为空
        if(count($data) < 1)
        {
            return array($leftMoney,$data);  
        }
 
        //如果是可以有剩余,并且$leftMoney > 0
        if('Can_Left' == $this->formatType
          && $leftMoney > 0)
        {
            return array($leftMoney,$data);  
        }
 
 
        //我的峰值
        $myMax = $this->maxMoney;
 
        // 如果还有余钱,则尝试加到小红包里,如果加不进去,则尝试下一个。
        while($leftMoney > 0)
        {
            $found = 0;
            foreach($data as $key => $val) 
            {
                //减少循环优化
                if($leftMoney <= 0)
                {
                    break;
                }
 
                //预判
                $afterLeftMoney =  (double)$leftMoney - 0.01;
                $afterVal = (double)$val + 0.01;
                if( $afterLeftMoney >= 0  && $afterVal <= $myMax)
                {
                    $found = 1;
                    $data[$key] = number_format($afterVal,2,'.','');
                    $leftMoney = $afterLeftMoney;
                    //精度
                    $leftMoney = number_format($leftMoney,2,'.','');
                }
            }
 
            //如果没有可以加的红包,需要结束,否则死循环
            if($found == 0)
            {
                break;
            }
        }
        //如果$leftMoney < 0 ,说明生成的红包超过预算了,需要减少部分红包金额
        while($leftMoney < 0)
        {
            $found = 0;
            foreach($data as $key => $val) 
            {
                if($leftMoney >= 0)
                {
                    break; 
                }
                //预判
                
                $afterLeftMoney =  (double)$leftMoney + 0.01;
                $afterVal = (double)$val - 0.01;
                if( $afterLeftMoney <= 0 && $afterVal >= $this->minMoney)
                {
                    $found = 1;
                    $data[$key] = number_format($afterVal,2,'.','');
                    $leftMoney = $afterLeftMoney;
                    $leftMoney = number_format($leftMoney,2,'.','');
                }
            }
            
            //如果一个减少的红包都没有的话,需要结束,否则死循环
            if($found == 0)
            {
                break;
            }
        }
        return array($leftMoney,$data);  
    }/*}}}*/
 
}/*}}}*/
 
//维护策略的环境类
class RedPackageBuilder
{/*{{{*/
 
    // 实例  
    protected static $_instance = null;  
 
    /** 
     * Singleton instance(获取自己的实例) 
     * 
     * @return MemcacheOperate 
     */  
    public static function getInstance()
    {  /*{{{*/
        if (null === self::$_instance) 
        {  
            self::$_instance = new self();  
        }  
        return self::$_instance;  
    }  /*}}}*/
 
    /** 
     * 获取策略【使用反射】
     * 
     * @param string $type 类型 
     * @return void 
     */  
    public function getBuilderStrategy($type)
    {  /*{{{*/
        $class = $type.'PackageStrategy';
 
        if(class_exists($class))
        {
            return new $class();  
        }
        else
        {
            throw new Exception("{$class} 类不存在!");
        }
    }  /*}}}*/
 
    public function getRedPackageByDTO(OptionDTO $optionDTO) 
    {/*{{{*/
        //获取策略
        $builderStrategy = $this->getBuilderStrategy($optionDTO->builderStrategy);
 
        //设置参数
        $builderStrategy->setOption($optionDTO);
 
        return $builderStrategy->create();
    }/*}}}*/
    
}/*}}}*/
 
class Client
{/*{{{*/
    public static function main($argv)
    {
        //固定红包
        $dto = OptionDTO::create(1000,10,100,100,'Equal');
        $data = RedPackageBuilder::getInstance()->getRedPackageByDTO($dto);
        //print_r($data);
 
        //随机红包[修数据]
        $dto = OptionDTO::create(5,10,0.01,0.99,'RandTriangle');
        $data = RedPackageBuilder::getInstance()->getRedPackageByDTO($dto);
        print_r($data);
 
        //随机红包[不修数据]
        $dto = OptionDTO::create(5,10,0.01,0.99,'RandTriangle','Can_Left');
        $data = RedPackageBuilder::getInstance()->getRedPackageByDTO($dto);
        //print_r($data);
        
    }
}/*}}}*/
 
Client::main($argv);
来源:https://blog.csdn.net/clevercode/article/details/53239681

点赞(0) 打赏

Comment list 共有 0 条评论

暂无评论

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部