Everyone has done this by seeking an algorithm for distributing red packets,
Is to give a total amount, a number of copies, the amount is automatically allocated randomly.
The minimum amount is 0.01 RMB.
Algorithm
Function ($ total, $ number of red packets ){
...
Return $ red packet array;
}
Reply to discussion (solution)
Function distribute ($ total, $ num)
{
If ($ num <= 0)
Return array ();
If ($ num = 1)
Return array ($ total );
$ N = rand (1, $ total * 100/2)/100;
$ Res [] = $ n;
If ($ num-1> = 0)
$ Res = array_merge ($ res, distribute ($ total-$ n), $ num-1 ));
Return $ res;
}
print_r(distribute(50, 40));
Array
(
[0] = & gt; 17.46
[1] => 7.1.
[2] => 10.39.
[3] = & gt; 4.44
[4] = & gt; 1.65
[5] = & gt; 0.14
[6] = & gt; 0.38
[7] = & gt; 0.46
[8] = & gt; 3.52
[9] = & gt; 0.34
[10] => 0.1.
[11] => 0.41.
[12] = & gt; 0.47
[13] = & gt; 1.21
[14] => 0.29.
[15] = & gt; 0.49
[16] = & gt; 0.45
[17] => 0.13.
[18] = & gt; 0.26
[19] = & gt; 0.08
[20] = & gt; 0.04
[21] = & gt; 0.08
[22] = & gt; 0.03
[23] = & gt; 0.02
[24] = & gt; 0.01
[25] = & gt; 0.02
[26] = & gt; 0.01
[27] = & gt; 0.01
[28] = & gt; 0.01
[29] = & gt; 0.01
[30] => 0.01.
[31] = & gt; 0.01
[32] = & gt; 0.01
[33] = & gt; 0.01
[34] => 0
[35] = & gt; 0.01
[36] => 0
[37] = & gt; 0.01
[38] = & gt; 0.01
[39] =>-0.080000000000006.
)
It is obviously wrong.
Function distribute ($ total, $ num)
{
If ($ num <= 0)
Return array ();
If ($ num = 1)
Return array ($ total );
$ N = rand (1, $ total * 100/2)/100;
$ Res [] = $ n;
If ($ num-1> = 0)
$ Res = array_merge ($ res, distribute ($ total-$ n), $ num-1 ));
Return $ res;
}
This may be better.
function distribute($total, $num) { $avg = $total / $num; $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; $r[$i+1] += $t; } $r[$num-1] = $total - array_sum(array_slice($r, 0, -1)); return $r;}
This may be better.
function distribute($total, $num) { $avg = $total / $num; $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; $r[$i+1] += $t; } $r[$num-1] = $total - array_sum(array_slice($r, 0, -1)); return $r;}
Incorrect result
I used var_dump.
100: 75
25:17
8: 4
4: 2
2:1
1:1
-1:1
-2: