您的位置:首页 > 移动开发 > 微信开发

微信红包的算法实现探讨

2016-07-01 15:15 489 查看
header("content-type:text/html;charset=utf8");

$statistics = array();      //统计红包次数

for($c=1 ;$c<=100 ;$c++){
$statistics = test($statistics);
echo "第 ".$c." 轮-----------------------------------------------------------
";
}

function test($statistics){
$total = 50;        //红包总额
$num   = 8;         //红包数量
$min   = 0.01;      //每个人最少能收到0.01元

for ($i=1 ;$i<$num ;$i++){
//TODO  此逻辑波动较大  $safe_totle = $total-($num-$i)*$min;    //随机安全上限    (大致意思就是 余额必须等于当前剩余红包*红包最小额度
//TODO  此逻辑越靠后数越大 $safe_totle = ($total-($num-$i)*$min)/($num-$i);    //随机安全上限  (总价-当前剩余红包最小额)/ 红包剩余量

$safe_totle = $total / ($num+1-$i) * 2;         //随机安全上限
$money = mt_rand($min*100,($safe_totle*100))/100;
$total = $total-$money;
echo '第'.$i.'个红包:'.$money.' 元,余额:'.$total.' 元
';
if(isset($statistics[$i]['money'])){
$statistics[$i]['money'] += $money;
}else{
$statistics[$i]['money'] = $money;
}

if(isset($max)){
if($money>$max['money']){
$max = array(
'money' => $money,
'id'    =>  $i,
);
}
}else{
$max = array(
'money' => $money,
'id'    =>  $i,
);
}
}
echo '第'.$num.'个红包:'.$total.' 元,余额:0 元
';
if(isset($statistics[$num]['money'])){
$statistics[$num]['money'] += $total;
}else{
$statistics[$num]['money'] = $total;
}

if($total>$max['money']){
$max = array(
'money' => $total,
'id'    =>  $num,
);
}

if(isset($statistics[$max['id']]['count'])){
$statistics[$max['id']]['count'] ++;
}else{
$statistics[$max['id']]['count'] = 1;
}

return $statistics;
}

print_r($statistics);

该程序 模拟领取 红包100次 每次 50元 8个红包

最后统计出 每个红包的总额 以及 幸运王的次数

该程序 借鉴微信文章 及 知乎大神的总结

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 微信