PHP写一个随机红包的算法

//红包金额,红包数量
function generateRedPackets($totalAmount, $count) {
        $min=0.01;
        if ($count <= 0 || $totalAmount <= 0) {
            return false;
        }
        if($totalAmount/$count<0.01)return false;
    
        $redPackets = [];
        $remainingAmount = $totalAmount;
        $remainingCount = $count;
    
        for ($i = 0; $i < $count - 1; $i++) {
            $max = $remainingAmount / $remainingCount * 2;
            //echo "{$i}.{$max}<br>";
            $randomAmount = mt_rand(1, intval($max*100)) / 100;
            $redPackets[] = round($randomAmount, 2);
            $remainingAmount -= $randomAmount;
            $remainingCount--;
        }
    
        $redPackets[] = round($remainingAmount, 2);
        if (abs(array_sum($redPackets) - $totalAmount)>$min || min($redPackets)<$min) {
            return generateRedPackets($totalAmount, $count);
        }
        return $redPackets;
}

因项目需要做一个随机红包功能,传入指定金额和指定红包数量,来生成随机的红包

用法:

$rt=generateRedPackets(1,11);
print_r($rt);

 结果如如下:

Array
(
    [0] => 0.06
    [1] => 0.12
    [2] => 0.17
    [3] => 0.11
    [4] => 0.1
    [5] => 0.02
    [6] => 0.11
    [7] => 0.05
    [8] => 0.16
    [9] => 0.01
    [10] => 0.09
)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值