<?php

/**
* 红包分配算法
*
* example
* $coupon = new Coupon(200, 5);
* $res = $coupon->handle();
* print_r($res);
* @author Flc <2018-04-06 20:09:53>
* @see http://flc.ren | http://flc.io | https://github.com/flc1125
*/
class Coupon
{
/**
* 红包金额
* @var float
*/
protected $amount; /**
* 红包个数
* @var int
*/
protected $num; /**
* 领取的红包最小金额
* @var float
*/
protected $coupon_min; /**
* 红包分配结果
* @var array
*/
protected $items = []; /**
* 初始化
* @param float $amount 红包金额(单位:元)最多保留2位小数
* @param int $num 红包个数
* @param float $coupon_min 每个至少领取的红包金额
*/
public function __construct($amount, $num = 1, $coupon_min = 0.01)
{
$this->amount = $amount;
$this->num = $num;
$this->coupon_min = $coupon_min;
} /**
* 处理返回
* @return array
*/
public function handle()
{
// A. 验证
if ($this->amount < $validAmount = $this->coupon_min * $this->num) {
throw new Exception('红包总金额必须≥'.$validAmount.'元');
} // B. 分配红包
$this->apportion(); return [
'items' => $this->items,
];
} /**
* 分配红包
*/
protected function apportion()
{
$num = $this->num; // 剩余可分配的红包个数
$amount = $this->amount; //剩余可领取的红包金额 while ($num >= 1) {
// 剩余一个的时候,直接取剩余红包
if ($num == 1) {
$coupon_amount = $this->decimal_number($amount);
} else {
$avg_amount = $this->decimal_number($amount / $num); // 剩余的红包的平均金额 $coupon_amount = $this->decimal_number(
$this->calcCouponAmount($avg_amount, $amount, $num)
);
}
$this->items[] = $coupon_amount; // 追加分配 $amount -= $coupon_amount;
--$num;
} shuffle($this->items); //随机打乱
} /**
* 计算分配的红包金额
*
* @param float $avg_amount 每次计算的平均金额
* @param float $amount 剩余可领取金额
* @param int $num 剩余可领取的红包个数
* @return float
*/
protected function calcCouponAmount($avg_amount, $amount, $num)
{
// 如果平均金额小于等于最低金额,则直接返回最低金额
if ($avg_amount <= $this->coupon_min) {
return $this->coupon_min;
} // 浮动计算
$coupon_amount = $this->decimal_number($avg_amount * (1 + $this->apportionRandRatio())); // 如果低于最低金额或超过可领取的最大金额,则重新获取
if ($coupon_amount < $this->coupon_min
|| $coupon_amount > $this->calcCouponAmountMax($amount, $num)
) {
return $this->calcCouponAmount($avg_amount, $amount, $num);
} return $coupon_amount;
} /**
* 计算分配的红包金额-可领取的最大金额
* @param float $amount
* @param int $num
*/
protected function calcCouponAmountMax($amount, $num)
{
return $this->coupon_min + $amount - $num * $this->coupon_min;
} /**
* 红包金额浮动比例
*/
protected function apportionRandRatio()
{
// 60%机率获取剩余平均值的大幅度红包(可能正数、可能负数)
if (rand(1, 100) <= 60) {
return rand(-70, 70) / 100; // 上下幅度70%
} return rand(-30, 30) / 100; // 其他情况,上下浮动30%;
} /**
* 格式化金额,保留2位
* @param float $amount
* @return float
*/
protected function decimal_number($amount)
{
return sprintf('%01.2f', round($amount, 2));
} } // 例子
$price_total = 0;
$total = $surplus_total = 30;
$max_num = $surplus_num = 8;
echo "总共{$total}元,随机生成{$max_num}个红包".'</br>'; for($i=0;$i<$max_num;$i++){
$coupon = new Coupon($surplus_total, $surplus_num, 0.01);
$res = $coupon->handle();
$money = $res['items'][0];
$price_total += $money;
$surplus_total = bcsub($surplus_total, $money, 2);  //解决高精度问题
echo '第'.($i+1).'个随机红包:'.$money.'还剩下'.($surplus_total).'元'.'<br>';
$surplus_num--;
}

示例演示:

php 随机红包算法的更多相关文章

  1. PHP实现微信随机红包算法和微信红包的架构设计简介

    微信红包的架构设计简介: 原文:https://www.zybuluo.com/yulin718/note/93148 @来源于QCon某高可用架构群整理,整理朱玉华. 背景:有某个朋友在朋友圈咨询微 ...

  2. PHP随机红包算法

    2017年1月14日 14:19:14 星期六 一, 整体设计 算法有很多种, 可以自行选择, 主要的"架构" 是这样的, 用redis decr()命令去限流, 用mysql去记 ...

  3. php 固定红包 + 随机红包算法

    <?php /** * 随机红包+固定红包算法[策略模式] * copyright (c) 2016 http://blog.csdn.net/CleverCode */ //配置传输数据DTO ...

  4. C# 随机红包算法

    static void Main(string[] args) { ; ; double minAmount = 0.01; Random r = new Random(); ; i < num ...

  5. 微信红包随机生成算法(PHP版)

    /** * 求一个数的平方 * @param $n */ function sqr($n){ return $n*$n; } /** * 生产min和max之间的随机数,但是概率不是平均的,从min到 ...

  6. 微信红包算法TEST

    1.基本算法 设定总金额为10元,有N个人随机领取:N=1 则红包金额=X元: N=2 为保证第二个红包可以正常发出,第一个红包金额=0.01至9.99之间的某个随机数 第二个红包=10-第一个红包金 ...

  7. PHP实现微信红包算法和微信红包的架构设计简介

    微信红包的架构设计简介: 原文:https://www.zybuluo.com/yulin718/note/93148 @来源于QCon某高可用架构群整理,整理朱玉华. 背景:有某个朋友在朋友圈咨询微 ...

  8. php红包算法函数[优化]

    php红包算法 <?php header("Content-Type: text/html;charset=utf-8");//输出不乱码,你懂的 $total=10000; ...

  9. php微信红包算法

    微信红包算法.php /**生成红包的函数*/ function getRandMoney($totalMoney, $totalPeople=2, $miniMoney=1){ $randRemai ...

随机推荐

  1. WinForm打包或部署

    一.新建InstallShield项目 二. 三. 四. 五. 六. 七. 最后重新生成,安装包一般在E\Setup1\Setup1\Express\SingleImage\DiskImages\DI ...

  2. 最近发现一个php trim的bug

    用trim 排除字符串两边的 “.”:你会发现“耀.”会出现编码错误问题,导致程序出现错误!代码如下: $a = "王者荣耀."; echo trim($a,".&quo ...

  3. vue table 固定首列和首行

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name ...

  4. js如何判断数字是否有小数

    //如果是5.00之类的,转换后,应该不要小数点后的位数 let num = 5.34; //let num = 5.00; let arr = num .toString().split(" ...

  5. BZOJ 1257 - 余数之和 - [CQOI2007]

    题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=1257 题意: 给定正整数 $n,k$,求 $(k \bmod 1) + (k \bmod ...

  6. CS(计算机科学)知识体

    附 录 A                   CS( 计算机科学)知识体 计算教程 2001 报告的这篇附录定义了计算机科学本科教学计划中可能讲授的知识领域.该分类方案的依据及其历史.结构和应用的其 ...

  7. 香茅油:不只是驱虫剂 new

    如果您是芳香疗法的爱好者,香茅油对您来说可能并不陌生.香茅油还经常被添加到各种个人护理和清洁产品中,给人们带来多种益处. 什么是香茅油? 香茅精油是从香茅属 (Cymbopogon ) 植物家族中提取 ...

  8. ide phpStorm常用代码片段设置

    1.打开设置(File -> Settings) 2.如图 3 . 最后,在PHP文件中输入 ll 并按 TAB 即可打出代码块

  9. JavaScript中的this所引用的对象和如何改变这个引用

    this是函数内部的一个特殊对象,它引用的是函数执行环境对象.也就是运行是基于函数的执行环境绑定. 1.在网页全局作用域中调用函数时,this引用window var color='black'; f ...

  10. 44-0-STM32的CAN外设

    1.RS-485 协议主要是把 RS-232 的信号改进成差分信号,从而大大提高了抗干扰特性: 在 RS-485 通讯网络中,节点中的串口控制器使用 RX 与 TX信号线连接到收发器上,而收发器通过差 ...