可自定义概率,按需求排除奖项 无 ?php/** * 抽奖函数升级版,可排除若干奖项 */class Lottery { static public $rate; static public $ignore; /** * * @param type $rate 概率设置 * @param type $ignore 忽略的奖项 * @return 调用实例化后的对象方法 * @e
可自定义概率,按需求排除奖项
<?php /** * 抽奖函数升级版,可排除若干奖项 */ class Lottery { static public $rate; static public $ignore; /** * * @param type $rate 概率设置 * @param type $ignore 忽略的奖项 * @return 调用实例化后的对象方法 * @example Lottery::runOnce(array(20, 10, 10, 10), array(0)); */ static public function runOnce($rate = array(10, 10, 10, 10), $ignore = array()) { self::$rate = $rate; self::$ignore = $ignore; $obj = new self; return $obj->lotteryProcess(); } /** * 处理抽奖 * @return type */ public function lotteryProcess() { $rateSum = array_sum(self::$rate); //概率之和 //考虑用户输入的概率之和不等于100 if ($rateSum < 100) { array_push(self::$rate, 100 - $rateSum); } elseif ($rateSum > 100) { die('The rate sum over 100%!'); } //处理忽略奖项 $rateCount = count(self::$rate); foreach (self::$rate as $key => $value) { if (in_array($key, self::$ignore)) { self::$rate[$rateCount - 1]+=self::$rate[$key]; self::$rate[$key] = 0; } $seedRaw[$key] = self::$rate[$key] * 100; //概率放大100被备用 } $seed = $this->arraySum($seedRaw); //处理数组 $randVal = mt_rand(0, 10000); return $this->judge($seed, $randVal); } /** * 从0-10000重新组织数组,每个值为之前各项的累加 * @param array $seedRaw * @return array */ private function arraySum(array$seedRaw) { foreach ($seedRaw as $key => $value) { $tmpSum = 0; for ($i = 0; $i < $key; $i++) { $tmpSum+=$seedRaw[$i]; } $seed[$key] = $tmpSum; } array_push($seed, 10000); return $seed; } /** * 根据随机值判断此次中了第几个奖项 * @param type $seed * @param type $rand * @return int */ private function judge($seed, $rand) { array_push($seed, NULL); //凑数 for ($i = 0; $i < count($seed) - 1; $i++) { if ($rand >= $seed[$i] && $rand < $seed[$i + 1]) { return $i; } } } } ini_set('display_errors', 'on'); $l0 = 0; $l1 = 0; $l2 = 0; $l3 = 0; $l4 = 0; $l5 = 0; for ($i = 0; $i <= 10000; $i++) { $result = Lottery::runOnce(array(20, 10, 10, 10), array(0, 1)); if ($result === 0) $l0++; if ($result == 1) $l1++; if ($result == 2) $l2++; if ($result == 3) $l3++; if ($result == 4) $l4++; } echo '0:' . $l0 . '<br/>1:' . $l1 . '<br/>2:' . $l2 . '<br/>3:' . $l3 . '<br/>4:' . $l4;