php实现红包算法
红包算法实现思路
红包算法的核心在于公平性和随机性,常见的有固定金额和随机金额两种模式。以下介绍几种常见的红包算法实现方法。
固定金额红包
固定金额红包是指每个红包的金额相同,实现较为简单。

function fixedRedPacket($totalAmount, $totalPeople) {
if ($totalPeople <= 0) {
return [];
}
$eachAmount = $totalAmount / $totalPeople;
return array_fill(0, $totalPeople, $eachAmount);
}
随机金额红包(普通版)
随机金额红包需要保证每个人至少分到一定金额,且总金额等于预设值。

function randomRedPacket($totalAmount, $totalPeople) {
if ($totalPeople <= 0) {
return [];
}
$result = [];
$remainingAmount = $totalAmount;
$remainingPeople = $totalPeople;
for ($i = 0; $i < $totalPeople - 1; $i++) {
$max = $remainingAmount - $remainingPeople + 1;
$money = mt_rand(1, $max * 100) / 100;
$result[] = $money;
$remainingAmount -= $money;
$remainingPeople--;
}
$result[] = $remainingAmount;
shuffle($result);
return $result;
}
二倍均值法
二倍均值法是一种更公平的随机红包算法,保证每次随机金额在合理范围内。
function doubleAverageRedPacket($totalAmount, $totalPeople) {
if ($totalPeople <= 0) {
return [];
}
$result = [];
$remainingAmount = $totalAmount;
$remainingPeople = $totalPeople;
for ($i = 0; $i < $totalPeople - 1; $i++) {
$avg = $remainingAmount / $remainingPeople * 2;
$money = mt_rand(1, $avg * 100) / 100;
$result[] = $money;
$remainingAmount -= $money;
$remainingPeople--;
}
$result[] = $remainingAmount;
shuffle($result);
return $result;
}
线段切割法
线段切割法将总金额视为一条线段,随机选择分割点生成红包金额。
function lineCutRedPacket($totalAmount, $totalPeople) {
if ($totalPeople <= 0) {
return [];
}
$points = [];
for ($i = 0; $i < $totalPeople - 1; $i++) {
$points[] = mt_rand(1, $totalAmount * 100) / 100;
}
sort($points);
$result = [];
$prev = 0;
foreach ($points as $point) {
$result[] = $point - $prev;
$prev = $point;
}
$result[] = $totalAmount - $prev;
shuffle($result);
return $result;
}
注意事项
- 所有红包算法需保证总金额与预设值一致,避免浮点数精度问题。
- 随机红包算法需确保每个人至少分到0.01元。
- 可根据实际需求调整随机范围和分配策略。






