/**
* 随机红包
*
* @param int $n 红包数
* @param float $totalMoney 总钱数
* @return array
*/
function hongBao($n, $totalMoney)
{
if ($n > 100) {
return '红包数大于100!';
}
$result = array();
if ($n == 1) {
array_push($result, number_format($totalMoney, 2));
} else {
//后缀小数位
$suffixNumber = $totalMoney / $n < 0.1 ? 3 : 2;
for ($i = 1; $i <= $n; $i++) {
//随机系数
$coefficient = lcg_value() + lcg_value();
//最大系数
$coefficient = $coefficient >= 1.70 ? 1.25 : $coefficient;
//最后一次
if ($i == $n) {
//防止溢出
if (array_sum($result) > $totalMoney) {
return hongBao($n, $totalMoney);
break;
}
$data = $totalMoney - array_sum($result);
} else {
$data = $coefficient * ($totalMoney / $n);
}
//防止等于0
if (in_array(number_format($data, $suffixNumber), array(0.00, 0.000))) {
$data += 0.01;
}
array_push($result, number_format($data, $suffixNumber));
}
}
return $result;
}
转载于:https://my.oschina.net/wangyandong/blog/549174