php實現自訂中獎項數和機率的抽獎函數詳解

來源:互聯網
上載者:User
這篇文章主要介紹了php實現自訂中獎項數和機率的抽獎函數,涉及php字串、數組的機率運算相關操作技巧,需要的朋友可以參考下

具體如下:

<?php/** 一個抽獎類,精確到萬分之一* 三個步驟:1.接受一個中獎機率數組;2.接受一個抽獎種子;3.返回中獎等級*/class Lottery {/** 中獎機率數組,自動判斷獎項數目* 數組索引值和為100,自動計算出不中獎的機率,若初始是超過100拋出一個錯誤*/protected $_rate = array();/** 設定中獎機率,* @param Array,中獎機率,以數組形式傳入*/public function setRate($rate = array(12.1, 34)) {$this->_rate = $rate;if (array_sum($this->_rate) > 100)//檢測機率設定是否有問題throw new Exception('Winning rate upto 100%');if (array_sum($this->_rate) < 100)//定義未中獎情況的機率,使用者給的機率只和為100時,則忽略0$this->_rate[] = 100 - array_sum($this->_rate);}/** 隨機產生一個1-10000的整數種子,提交給中獎判斷函數* @return int,按傳入的機率排序,返回中獎的項數*/public function runOnce() {return $this->judge(mt_rand(0, 10000));}/** 按所設定的機率,判斷一個傳入的隨機值是否中獎* @param int,$seed 10000以內的隨機數* @return int,$i 按傳入的機率排序,返回中獎的項數*/protected function judge($seed) {foreach ($this->_rate as $key => $value) {$tmpArr[$key + 1] = $value * 100;}//將機率乘十後累計,以便隨機播放,組合成$tmpArr[0] = 0;foreach ($tmpArr as $key => $value) {if ($key > 0) {$tmpArr[$key] += $tmpArr[$key - 1];}}for ($i = 1; $i < count($tmpArr); $i++) {if ($tmpArr[$i - 1] < $seed && $seed <= $tmpArr[$i]) {return $i; //返回中獎的項數(按機率的設定順序)}}}}$rate = array(33, 20, 2, 0.95, 12, 4.55);$a = new Lottery;$a->setRate($rate);for ($i = 0; $i <= 10000; $i++) {$b = $a->runOnce();@$rewards[$b]++;}unset($rewards['']);echo array_sum($rewards);?><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf8" /></head><body><table><thead>運行10000次,對比設定機率和中獎次數</thead><tr><th>設定機率</th><th>中獎次數</th></tr><tr><td><?php echo $rate[0]; ?>%</td><td><?php echo $rewards[1] ?></td></tr><tr><td><?php echo $rate[1]; ?>%</td><td><?php echo $rewards[2] ?></td></tr><tr><td><?php echo $rate[2]; ?>%</td><td><?php echo $rewards[3] ?></td></tr><tr><td><?php echo $rate[3]; ?>%</td><td><?php echo $rewards[4] ?></td></tr><tr><td><?php echo $rate[4]; ?>%</td><td><?php echo $rewards[5] ?></td></tr><tr><td><?php echo $rate[5]; ?>%</td><td><?php echo $rewards[6] ?></td></tr><tr><td><?php echo 'miss'; ?></td><td><?php echo $rewards[7] ?></td></tr></table></body></html>

相關推薦:

PHP實現計算抽獎機率演算法

按機率產生數字

js實現數字機率計算

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.