php微信红包算法
Posted sfornt
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php微信红包算法相关的知识,希望对你有一定的参考价值。
微信红包算法.php
/**生成红包的函数*/
function getRandMoney($totalMoney, $totalPeople=2, $miniMoney=1){
$randRemainMoney = $totalMoney - $totalPeople * $miniMoney;//剩余需要随机的钱数
return _getRandMoney($randRemainMoney, $totalPeople, $miniMoney);
}
/**红包生成的逻辑代码*/
function _getRandMoney($totalMoney, $totalPeople, $miniMoney){
$returnMessage = array('status'=>1, 'data'=>NULL);
if($totalMoney > 0){
$returnMessage['data'] = _randMoney($totalMoney, $totalPeople, $miniMoney);
}elseif($totalMoney == 0){
$returnMessage['data'] = array_fill(0, $totalPeople, 1);
}else{
$returnMessage['status'] = -1;
$returnMessage['data'] = '参数传递有误,生成红包失败';
}
return $returnMessage;
}
/*参数无误,开始生成对应的红包金额*/
function _randMoney($totalMoney, $totalPeople, $miniMoney){
$data = array_fill(0, $totalPeople, $miniMoney);
if($totalPeople > 1){
foreach($data as $k => $v){
if($k == $totalPeople -1){
$data[$k] = $totalMoney + $v;
break;
}else {
if($totalMoney == 0) break;
$randMoney = rand(0, $totalMoney);
$totalMoney -= $randMoney;
$data[$k] = $randMoney + $v;
}
}
}
return $data;
}
以上是关于php微信红包算法的主要内容,如果未能解决你的问题,请参考以下文章
春节期间小明使用微信收到很多个红包,非常开心。在查看领取红包记录时发现,某个红包金额出现的次数超过了红包总数的一半。请帮小明找到该红包金额。写出具体算法思路和代码实现,要求算法尽可能高效。