20,398
社区成员




$total=10;//红包总额
$num=8;// 分成8个红包,支持8人随机领取
$min=0.01;//每个人最少能收到0.01元
for ($i=1;$i<$num;$i++)
{
$safe_total=($total-($num-$i)*$min)/($num-$i);//随机安全上限
$money=mt_rand($min*100,$safe_total*100)/100;
$total=$total-$money;
echo '第'.$i.'个红包:'.$money.' 元,余额:'.$total.' 元 <br/>';
}
echo '第'.$num.'个红包:'.$total.' 元,余额:0 元';
在知乎上看到的。。http://www.zhihu.com/question/22625187
这是设定了一个最小值。。
$total = 10000;
$copies = 60;
$min = 1;
$max = 200;
$r = Redbag($total, $copies, $min, $max);
printf("项数:%s 合计%d 最大:%d 最小:%d\n", count($r), array_sum($r), max($r), min($r));
print_r($r);
function Redbag($total, $copies, $min, $max) {
$res = array_fill(0, $copies, $min);
while(array_sum($res) < $total) {
$k = rand(0, $copies - 1);
if(++$res[$k] > $max) $res[$k]--;
}
return $res;
}