本文實(shí)例講述了php實(shí)現(xiàn)的微信紅包算法。分享給大家供大家參考。具體如下:
最近一直在微信群里體驗(yàn)紅包功能,紅包類(lèi)型有兩種:
1. 普通紅包
2. 拼手氣紅包
普通紅包就不用多解析了,大鍋飯?jiān)恚椒帧?/p>
拼手氣紅包講的是手氣(運(yùn)氣),有人可以搶到很多,有人搶的少得可憐,當(dāng)然也不是先搶就一定多,說(shuō)到底了就是隨機(jī)。
想了想,自己寫(xiě)寫(xiě)看,能不能實(shí)現(xiàn)類(lèi)似的功能(不敢說(shuō)是算法)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
// $bonus_total 紅包總金額 // $bonus_count 紅包個(gè)數(shù) // $bonus_type 紅包類(lèi)型 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è)紅包多少錢(qián) $i = 0; while ( $i < $bonus_count ){ if ( $i < $bonus_count -1){ $rand = $bonus_type ?(rand(1, $bonus_balance *100-1)/100): $bonus_avg ; // 根據(jù)紅包類(lèi)型計(jì)算當(dāng)前紅包的金額 $bonus_items [] = $rand ; $bonus_balance -= $rand ; } else { $bonus_items [] = $bonus_balance ; // 最后一個(gè)紅包直接承包最后所有的金額,保證發(fā)出的總金額正確 } $i ++; } return $bonus_items ; } |
好吧,我們現(xiàn)在來(lái)體驗(yàn)一下
1
2
3
4
5
6
|
// 發(fā)3個(gè)拼手氣紅包,總金額是100元 $bonus_items = randBonus(100, 3, 1); // 查看生成的紅包 var_dump( $bonus_items ); // 校驗(yàn)總金額是不是正確,看看微信有沒(méi)有坑我們的錢(qián) var_dump( array_sum ( $bonus_items )); |
另一個(gè)使用數(shù)組實(shí)現(xiàn)的版本,原理差不多:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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ì)有所幫助。