Then ask the red envelope algorithm, the previous bug, @JXYCYFLM, @
http://bbs.csdn.net/topics/391001579
The previous post is here.
There are problems with the two-bit algorithm.
The revised version given by the moderator is wrong whenever the number of red envelopes is singular. Add up is not equal to total.
Two heroes are kindly requested to help correct.
------to solve the idea----------------------
$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;
}
------to solve the idea----------------------
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);
------to solve the idea----------------------
In the entertainment type Red envelope code
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;
}