紅包演算法的一種實現(PHP)

來源:互聯網
上載者:User

標籤:pre   sort   時間   tps   單點   net   https   沒有   rand   

        前段時間有個項目需要用到紅包演算法,本以為簡單,細想之下有點複雜。於是就百度了一下,沒想到查出了不少,有些寫的很複雜。由於時間有點緊,我就找了一個簡單點的。然後參考著寫一個。參考的地址是:52954413;

       這個地址中的紅包是用java寫的。根據其原理,我用PHP寫了一遍,並且改進了點。他的演算法中沒有加每個紅包最大最小值限制。我用PHP寫的時候加上去了。代碼如下:

<?php/*$total_money:紅包總金額$total_people:總人數/總分數$min_money:每份紅包的最小金額$max_money:每份紅包的最大金額*/function redpack($total_money,$total_people,$min_money,$max_money){   $ret=array();   $new_ret=array();      $total_real_money=$total_money-$total_people*$min_money;   $ret[0]=0;   for($i=1;$i<$total_people;$i++){            $ret[$i]=get_rand($ret[$i-1],$total_real_money,($max_money-$min_money));              } sort($ret);for($j=0;$j<count($ret);$j++){if($j==count($ret)-1){$new_ret[count($ret)-1]=$total_real_money-$ret[count($ret)-1]+$min_money;}else{    $new_ret[]=$ret[$j+1]-$ret[$j]+$min_money;}}shuffle($new_ret);  return $new_ret;}function get_rand($start,$end,$max){    $tmp=rand($start,$end);    $total_max=$start+$max;        if($tmp>($total_max) || empty($tmp)){        return get_rand($start,$end,$max);    }else{        return $tmp;    }    }


紅包演算法的一種實現(PHP)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.