php實現(xiàn)的微信紅包算法分析(非官方)
更新時間:2015年09月25日 11:04:47 作者:deeka
這篇文章主要介紹了php實現(xiàn)的微信紅包算法,以實例形式分析了拼手氣紅包的相關隨機算法技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了php實現(xiàn)的微信紅包算法。分享給大家供大家參考。具體如下:
最近一直在微信群里體驗紅包功能,紅包類型有兩種:
1. 普通紅包
2. 拼手氣紅包
普通紅包就不用多解析了,大鍋飯原理,平分。
拼手氣紅包講的是手氣(運氣),有人可以搶到很多,有人搶的少得可憐,當然也不是先搶就一定多,說到底了就是隨機。

想了想,自己寫寫看,能不能實現(xiàn)類似的功能(不敢說是算法)。
// $bonus_total 紅包總金額
// $bonus_count 紅包個數(shù)
// $bonus_type 紅包類型 1=拼手氣紅包 0=普通紅包
function randBonus($bonus_total=0, $bonus_count=3, $bonus_type=1){
$bonus_items = array(); // 將要瓜分的結果
$bonus_balance = $bonus_total; // 每次分完之后的余額
$bonus_avg = number_format($bonus_total/$bonus_count, 2); // 平均每個紅包多少錢
$i = 0;
while($i<$bonus_count){
if($i<$bonus_count-1){
$rand = $bonus_type?(rand(1, $bonus_balance*100-1)/100):$bonus_avg; // 根據(jù)紅包類型計算當前紅包的金額
$bonus_items[] = $rand;
$bonus_balance -= $rand;
}else{
$bonus_items[] = $bonus_balance; // 最后一個紅包直接承包最后所有的金額,保證發(fā)出的總金額正確
}
$i++;
}
return $bonus_items;
}
好吧,我們現(xiàn)在來體驗一下
// 發(fā)3個拼手氣紅包,總金額是100元 $bonus_items = randBonus(100, 3, 1); // 查看生成的紅包 var_dump($bonus_items); // 校驗總金額是不是正確,看看微信有沒有坑我們的錢 var_dump(array_sum($bonus_items));
另一個使用數(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;
}
希望本文所述對大家的php程序設計有所幫助。
相關文章
php基于curl重寫file_get_contents函數(shù)實例
這篇文章主要介紹了php基于curl重寫file_get_contents函數(shù)的方法,結合實例形式分析了php使用curl重寫file_get_contents函數(shù)實現(xiàn)屏蔽錯誤提示的相關技巧,需要的朋友可以參考下2016-11-11

