当前位置:Gxlcms > PHP教程 > 再问红包算法,之前的有bug,@JXYCYFLM,@,该怎么处理

再问红包算法,之前的有bug,@JXYCYFLM,@,该怎么处理

时间:2021-07-01 10:21:17 帮助过:20人阅读

再问红包算法,之前的有bug,@JXYCYFLM,@
http://bbs.csdn.net/topics/391001579
之前的帖子在此。


两位的算法都是有问题的。

版主给出的修订版,每当红包数量是单数的时候就不对了。加起来不等于总数。


恳请两位大侠帮忙修正。
------解决思路----------------------
$r = distribute(100, 31);
echo array_sum($r), PHP_EOL;
print_r($r);

function distribute($total, $num) {
$avg = $total / $num;
$r = array_fill(0, $num, round($avg, 2));

for($i=0; $i<$num; $i+=2) {
$t = rand(1, $avg * 100) / 100;
$r[$i] -= round($t, 2);
if($r[$i] <= 0) $r[$i] = 0.01;
if(isset($r[$i+1])) $r[$i+1] += round($t, 2);
}
$r[$num-1] = $total - array_sum(array_slice($r, 0, -1));
return $r;
}

$r = distribute(100, 31);
echo array_sum($r), PHP_EOL;
print_r($r);

function distribute($total, $num) {
$avg = round($total / $num, 2);
$r = array_fill(0, $num, $avg);

for($i=0; $i<$num; $i+=2) {
$t = rand(1, $avg * 100) / 100;
$r[$i] -= $t;
if($r[$i] <= 0) $r[$i] = 0.01;
if(isset($r[$i+1])) $r[$i+1] += $t;
}
$r[$num-1] = $total - array_sum(array_slice($r, 0, -1));
return $r;
}

------解决思路----------------------

function distribute($total,$num){
return _distribute($total,$num,$total/$num/2,0);
}
function _ceil($i){
return ((int)($i*100))/100;
}
function _distribute($total,$num,$pj,$last_c){
if($num==0){
return array();
}
else if($num==1){
return array($total);
}
else {
$cz=_ceil(mt_rand(-$pj*100,$pj*100)/100);
$n=_ceil($pj+$cz+$last_c);
$res[]=$n;
if($num-1>=0)
$res=array_merge($res,_distribute($total-$n,$num-1,$pj,$pj-$cz));
return $res;
}
}
$ary=distribute(50,12);
print_r(array_sum($ary));
print_r($ary);

------解决思路----------------------
奉上娱乐型红包代码


function fn($total, $part, $min = 0.01) {
$res = array_fill(0, $part, $min);
$total -= $part * $min;
for($i=0; $i<$part; $i++) $total -= ($res[$i] += round($i == $part - 1 ? $total : (rand(0, $total * 100)) / 100, 2)) - $min;
return $res;
}

人气教程排行