php 随机红包算法
<?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 随机红包算法的更多相关文章
- PHP实现微信随机红包算法和微信红包的架构设计简介
微信红包的架构设计简介: 原文:https://www.zybuluo.com/yulin718/note/93148 @来源于QCon某高可用架构群整理,整理朱玉华. 背景:有某个朋友在朋友圈咨询微 ...
- PHP随机红包算法
2017年1月14日 14:19:14 星期六 一, 整体设计 算法有很多种, 可以自行选择, 主要的"架构" 是这样的, 用redis decr()命令去限流, 用mysql去记 ...
- php 固定红包 + 随机红包算法
<?php /** * 随机红包+固定红包算法[策略模式] * copyright (c) 2016 http://blog.csdn.net/CleverCode */ //配置传输数据DTO ...
- C# 随机红包算法
static void Main(string[] args) { ; ; double minAmount = 0.01; Random r = new Random(); ; i < num ...
- 微信红包随机生成算法(PHP版)
/** * 求一个数的平方 * @param $n */ function sqr($n){ return $n*$n; } /** * 生产min和max之间的随机数,但是概率不是平均的,从min到 ...
- 微信红包算法TEST
1.基本算法 设定总金额为10元,有N个人随机领取:N=1 则红包金额=X元: N=2 为保证第二个红包可以正常发出,第一个红包金额=0.01至9.99之间的某个随机数 第二个红包=10-第一个红包金 ...
- PHP实现微信红包算法和微信红包的架构设计简介
微信红包的架构设计简介: 原文:https://www.zybuluo.com/yulin718/note/93148 @来源于QCon某高可用架构群整理,整理朱玉华. 背景:有某个朋友在朋友圈咨询微 ...
- php红包算法函数[优化]
php红包算法 <?php header("Content-Type: text/html;charset=utf-8");//输出不乱码,你懂的 $total=10000; ...
- php微信红包算法
微信红包算法.php /**生成红包的函数*/ function getRandMoney($totalMoney, $totalPeople=2, $miniMoney=1){ $randRemai ...
随机推荐
- Digest of Overview of Linux Kernel Security Features
Linux kernel Security: I. DAC: Discretionary Access Control, the core security model of UNIX. II. PO ...
- Java第四次实践作业
1 编写“电费管理类”及其测试类. 第一步 编写“电费管理”类 1)私有属性:上月电表读数.本月电表读数 2)构造方法:无参.2个参数 3)成员方法:getXXX()方法.setXXX()方法 4 ...
- RMAN备份filesperset用法
用filesperset控制备份集的尺寸 当指定filesperset参数时,rman比较filesperset与自动计算出来的值(对每个已分配通道的文件数目) 并取其中较小的那个值来保证所有的通道被 ...
- ASA failover --AA
1.A/A Failover 介绍 安全设备可以成对搭配成A/A的FO来提供设备级的冗余和负载分担. 两个设备在互为备份的同时,也能同时转发流量. 使用虚拟子防火墙是必须的,子防火墙被归为两个FO组 ...
- ASA failover
Active-Standby 1.作用:提供设备冗余 2.物理概念:primary 和 secondary ,需要命令敲得,角色不会切换, 3.虚拟概念:active和standby ,需要选举,角色 ...
- Openshift 错误解决 "修改docker cgroup driver"
一.Openshift 错误解决 "修改docker cgroup driver" 一.错误如下 failed to run Kubelet: failed to create k ...
- 【心得】-NO.114.面试.1 -【To HR And Interviewer】
Style:Mac Series:Java Since:2018-09-10 End:2018-09-10 Total Hours:1 Degree Of Diffculty:5 Degree Of ...
- 【LeetCode每天一题】Permutation Sequence(排列序列)
The set [1,2,3,...,n] contains a total of n! unique permutations.By listing and labeling all of the ...
- python 图像处理,画一个正弦函数
import numpy as np from PIL import Image import matplotlib.pyplot as plt import math size = 300 new_ ...
- 图表管理账单的NABCD
首先,我们团队的项目目标是记账本.就我个人理解,记账本中心功能有两项,第一,记录:第二,显示.而本篇博客主要描述用各种不同的图表来显示的NABCD. 首先是N(need),用户的需求就是我们的动力!利 ...