我与随机红包算法的故事
背景故事:
- 期初,为了快速实现,我采用的算法是只要满足最小值,可以分配完金额,并且不超额即可 (算法一)
- 中期,发现算法一有个严重的问题,越往后领取红包,金额越小,并且后面出现大量的最小值问题,使用 N 倍均值法解决(算法二)
- 后期,加入领取红包最大值的控制条件,只允许每个红包的最大金额为 200 元(算法三)
- 以下说明,均为算法三的。细细品算法三,就能看到算法二与算法一的影子
算法要点:
- 满足:红包的总金额 === 领取红包总额
- 满足:红包的总金额 ≥ 红包最小金额 * 领取红包的人数
- 满足:红包的总金额 ≤ 红包最大金额 * 领取红包的人数
- 满足:红包领取的最小金额 ≤ 红包领取的最大金额
算法分析:
- 计算随机值:每一个随机值,都是在最小值与最大值之间取一个值出来的(apportion 方法)
- 计算最小值:在没有最大值时,可以直接使用传入的最小值;如果有,就需要考虑其他次数都获取到最大值后所剩下的值的情况。如果剩下的值 > 初始最小值,那它替代掉初始最小值(calcMin 方法)
- 计算最大值:计算最大值方法需要的最小值,必须是上一步计算出来的最小值。最大值的计算,是整个算法的核心所在。为了值分布得均匀一些,我们使用的是N倍均值算法。计算出平均值,然后乘以倍率,即可得出最大值。计算出来的最大值,还必须小于等于其他次数领取到最小值后剩下的值(calcMax 方法)
- 为了方便计算,代码使用了以分为单位,并在最后格式化输出
- 好羞涩难懂的表述啊,还是直接上算法代码吧
算法使用:
$amount = 10000;
$count = 10;
$min = 1;
$max = 500;
$avgMultiple = 2;
$needFormat = true;
$service = new DivideCandyService($amount,$count,$min,$max,$avgMultiple,$needFormat);
$values = $service->handle();
算法代码(php):
<?php
class DivideCandyService
{
protected $amount;
protected $count;
protected $min;
protected $max;
protected $avgMultiple;
protected $needFormat;
protected $items = [];
public function __construct(
int $amount,
int $count = 1,
int $min = 1,
int $max = 0,
float $avgMultiple = 2,
bool $needFormat = true
) {
$this->amount = $amount;
$this->count = $count;
$this->min = $min;
$this->max = $max;
$this->avgMultiple = $avgMultiple;
$this->needFormat = $needFormat;
}
public function handle()
{
$totalMin = $this->min * $this->count;
if ($this->amount < $totalMin) {
throw new \Exception('总数太小了');
}
if ($this->max > 0) {
$totalMax = $this->max * $this->count;
if ($this->amount > $totalMax) {
throw new \Exception('总数太大了');
}
}
$this->apportion();
return $this->items;
}
protected function apportion()
{
$count = $this->count;
$amount = $this->amount;
while ($count >= 1) {
if ($count === 1) {
$randomValue = $amount;
} else {
$calcMin = $this->calcMin($amount, $count, $this->min, $this->max);
$calcMax = $this->calcMax($amount, $count, $calcMin, $this->max);
$randomValue = random_int($calcMin, $calcMax);
}
$this->items[] = $this->formatValue($randomValue);
$amount -= $randomValue;
--$count;
}
shuffle($this->items);
}
protected function calcMin(int $amount, int $count, int $min, int $max): int
{
if ($max <= 0) {
return $min;
}
$otherTotalMax = ($count - 1) * $max;
$newMin = $amount - $otherTotalMax;
if ($newMin > $min) {
return $newMin;
}
return $min;
}
protected function calcMax(int $amount, int $count, int $min, int $max): int
{
$totalMin = $min * $count;
if ($amount <= $totalMin) {
return $min;
}
$otherTotalMin = ($count - 1) * $min;
$calcAmount = $amount - $otherTotalMin;
$avg = $amount / $count;
$calcMax = (int)($avg * $this->avgMultiple);
$calcMax = $calcMax > $calcAmount ? $calcAmount : $calcMax;
if ($max <= 0 || ($calcMax <= $max && $calcMax >= $min)) {
return $calcMax;
}
return $max;
}
protected function formatValue(int $value)
{
if ($this->needFormat) {
return (float)bcdiv((string)$value, '100', 2);
}
return $value;
}
}