這篇文章主要介紹了php實現的微信紅包算法,以實例形式分析了拼手氣紅包的相關隨機算法技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了php實現的微信紅包算法。分享給大家供大家參考。具體如下:
最近一直在微信群里體驗紅包功能,紅包類型有兩種:
1. 普通紅包
2. 拼手氣紅包
普通紅包就不用多解析了,大鍋飯原理,平分。
拼手氣紅包講的是手氣(運氣),有人可以搶到很多,有人搶的少得可憐,當然也不是先搶就一定多,說到底了就是隨機。
想了想,自己寫寫看,能不能實現類似的功能(不敢說是算法)。
- // $bonus_total 紅包總金額
- // $bonus_count 紅包個數
- // $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; // 根據紅包類型計算當前紅包的金額
- $bonus_items[] = $rand;
- $bonus_balance -= $rand;
- }else{
- $bonus_items[] = $bonus_balance; // 最后一個紅包直接承包最后所有的金額,保證發出的總金額正確
- }
- $i++;
- }
- return $bonus_items;
- }
好吧,我們現在來體驗一下
- // 發3個拼手氣紅包,總金額是100元
- $bonus_items = randBonus(100, 3, 1);
- // 查看生成的紅包
- var_dump($bonus_items);
- // 校驗總金額是不是正確,看看微信有沒有坑我們的錢
- var_dump(array_sum($bonus_items));
另一個使用數組實現的版本,原理差不多:
- 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程序設計有所幫助。
新聞熱點
疑難解答