随机红包算法
简单模仿微信发送随机红包写的算法
/**
* 随机红包算法
* $mony分钱随机发给$count个人,$height越大,随机金额大小分化越大
*/
function rand_redpack($mony,$count = 30, $height = 4){
if($mony < $count) return false; //不够分
if($height <= 0) return false; //$height只能大于或等于0
$arr = [];
for ($x=0; $x<$count; $x++) $arr[] = 1;
$restMony = $mony - $count;
$roll = function($arr, $restMony) use (&$roll, $height) { //匿名递归写法
if($restMony === 0) return $arr;
$index = rand(0,count($arr)-1);
$passe = ceil($height*round($restMony/count($arr)));
$spend = $restMony>=$passe ? rand(1, $passe) : rand(1, $restMony);
$arr[$index] += $spend;
return $roll($arr, $restMony-$spend);
};
return $roll($arr, $restMony);
};
//假如我们把50元红包发给30个人
rand_redpack(5000, 30, 4);
结果
array:30 [
0 => 99
1 => 176
2 => 14
3 => 160
4 => 231
5 => 65
6 => 178
7 => 36
8 => 1
9 => 95
10 => 43
11 => 23
12 => 92
13 => 220
14 => 16
15 => 638
16 => 49
17 => 1
18 => 528
19 => 19
20 => 2
21 => 505
22 => 620
23 => 41
24 => 9
25 => 451
26 => 181
27 => 55
28 => 104
29 => 348
]
rand_redpack(5000, 30, 0.1);
array:30 [
0 => 194
1 => 154
2 => 134
3 => 130
4 => 177
5 => 178
6 => 178
7 => 122
8 => 174
9 => 201
10 => 154
11 => 176
12 => 164
13 => 211
14 => 146
15 => 157
16 => 233
17 => 198
18 => 121
19 => 189
20 => 108
21 => 99
22 => 155
23 => 165
24 => 163
25 => 185
26 => 171
27 => 162
28 => 230
29 => 171
]