模仿微信随机红包算法

随机红包算法


在这里插入图片描述

简单模仿微信发送随机红包写的算法


/**
 * 随机红包算法
 * $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
]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值