php實(shí)現(xiàn)的微信紅包算法分析(非官方)
本文實(shí)例講述了php實(shí)現(xiàn)的微信紅包算法。分享給大家供大家參考。具體如下:
最近一直在微信群里體驗(yàn)紅包功能,紅包類型有兩種:
1. 普通紅包
2. 拼手氣紅包
普通紅包就不用多解析了,大鍋飯?jiān)?,平分?/p>
拼手氣紅包講的是手氣(運(yùn)氣),有人可以搶到很多,有人搶的少得可憐,當(dāng)然也不是先搶就一定多,說到底了就是隨機(jī)。

想了想,自己寫寫看,能不能實(shí)現(xiàn)類似的功能(不敢說是算法)。
// $bonus_total 紅包總金額
// $bonus_count 紅包個(gè)數(shù)
// $bonus_type 紅包類型 1=拼手氣紅包 0=普通紅包
function randBonus($bonus_total=0, $bonus_count=3, $bonus_type=1){
$bonus_items = array(); // 將要瓜分的結(jié)果
$bonus_balance = $bonus_total; // 每次分完之后的余額
$bonus_avg = number_format($bonus_total/$bonus_count, 2); // 平均每個(gè)紅包多少錢
$i = 0;
while($i<$bonus_count){
if($i<$bonus_count-1){
$rand = $bonus_type?(rand(1, $bonus_balance*100-1)/100):$bonus_avg; // 根據(jù)紅包類型計(jì)算當(dāng)前紅包的金額
$bonus_items[] = $rand;
$bonus_balance -= $rand;
}else{
$bonus_items[] = $bonus_balance; // 最后一個(gè)紅包直接承包最后所有的金額,保證發(fā)出的總金額正確
}
$i++;
}
return $bonus_items;
}
好吧,我們現(xiàn)在來體驗(yàn)一下
// 發(fā)3個(gè)拼手氣紅包,總金額是100元 $bonus_items = randBonus(100, 3, 1); // 查看生成的紅包 var_dump($bonus_items); // 校驗(yàn)總金額是不是正確,看看微信有沒有坑我們的錢 var_dump(array_sum($bonus_items));
另一個(gè)使用數(shù)組實(shí)現(xiàn)的版本,原理差不多:
function sendRandBonus($total=0, $count=3, $type=1){
if($type==1){
$input = range(0.01, $total, 0.01);
if($count>1){
$rand_keys = (array) array_rand($input, $count-1);
$last = 0;
foreach($rand_keys as $i=>$key){
$current = $input[$key]-$last;
$items[] = $current;
$last = $input[$key];
}
}
$items[] = $total-array_sum($items);
}else{
$avg = number_format($total/$count, 2);
$i = 0;
while($i<$count){
$items[] = $i<$count-1?$avg:($total-array_sum($items));
$i++;
}
}
return $items;
}
希望本文所述對(duì)大家的php程序設(shè)計(jì)有所幫助。
相關(guān)文章
php基于curl重寫file_get_contents函數(shù)實(shí)例
這篇文章主要介紹了php基于curl重寫file_get_contents函數(shù)的方法,結(jié)合實(shí)例形式分析了php使用curl重寫file_get_contents函數(shù)實(shí)現(xiàn)屏蔽錯(cuò)誤提示的相關(guān)技巧,需要的朋友可以參考下2016-11-11
php遞歸函數(shù)中使用return的注意事項(xiàng)
php遞歸函數(shù)中使用return的時(shí)候會(huì)碰到無法正確返回想要的值得情況,下面就來舉例子來說明一下吧2014-01-01
php字符串分割函數(shù)explode的實(shí)例代碼
在php中分割一個(gè)字符串,我們可以使用函數(shù)explode(),其原型如下2013-02-02

