抢红包大家都玩过了,
就是给出一个总额,一个份数,就自动随机分配金额。
最小额0.01元。
求算法
function($总额,$红包个数){
。。。
return $红包数组;
}
回复讨论(解决方案)
function distribute($total,$num)
{
if($num 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));
登录后复制
(
[0] => 17.46
[1] => 7.1
[2] => 10.39
[3] => 4.44
[4] => 1.65
[5] => 0.14
[6] => 0.38
[7] => 0.46
[8] => 3.52
[9] => 0.34
[10] => 0.1
[11] => 0.41
[12] => 0.47
[13] => 1.21
[14] => 0.29
[15] => 0.49
[16] => 0.45
[17] => 0.13
[18] => 0.26
[19] => 0.08
[20] => 0.04
[21] => 0.08
[22] => 0.03
[23] => 0.02
[24] => 0.01
[25] => 0.02
[26] => 0.01
[27] => 0.01
[28] => 0.01
[29] => 0.01
[30] => 0.01
[31] => 0.01
[32] => 0.01
[33] => 0.01
[34] => 0
[35] => 0.01
[36] => 0
[37] => 0.01
[38] => 0.01
[39] => -0.080000000000006
)
显然是错误的
function distribute($total,$num)
{
if($num 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;
}
改成这样可能好些
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;}
登录后复制
登录后复制
改成这样可能好些
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;}
登录后复制
登录后复制
结果不对
我用var_dump出来
100:75
25:17
8:4
4:2
2:1
1:1
0:1
-1:1
-2:0