欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

一个抽奖函数(自定义中奖项数和概率)

程序员文章站 2022-06-05 17:52:43
...
适用于抽奖系统
  1. /*
  2. * 一个抽奖类,精确到万分之一
  3. * 三个步骤:1.接受一个中奖概率数组;2.接受一个抽奖种子;3.返回中奖等级
  4. */
  5. class Lottery {
  6. /*
  7. * 中奖概率数组,自动判断奖项数目
  8. * 数组键值和为100,自动计算出不中奖的概率,若初始是超过100抛出一个错误
  9. */
  10. protected $_rate = array();
  11. /*
  12. * 设置中奖概率,
  13. * @param Array,中奖概率,以数组形式传入
  14. */
  15. public function setRate($rate = array(12.1, 34)) {
  16. $this->_rate = $rate;
  17. if (array_sum($this->_rate) > 100)//检测概率设置是否有问题
  18. throw new Exception('Winning rate upto 100%');
  19. if (array_sum($this->_rate) //定义未中奖情况的概率,用户给的概率只和为100时,则忽略0
  20. $this->_rate[] = 100 - array_sum($this->_rate);
  21. }
  22. /*
  23. * 随机生成一个1-10000的整数种子,提交给中奖判断函数
  24. * @return int,按传入的概率排序,返回中奖的项数
  25. */
  26. public function runOnce() {
  27. return $this->judge(mt_rand(0, 10000));
  28. }
  29. /*
  30. * 按所设置的概率,判断一个传入的随机值是否中奖
  31. * @param int,$seed 10000以内的随机数
  32. * @return int,$i 按传入的概率排序,返回中奖的项数
  33. */
  34. protected function judge($seed) {
  35. foreach ($this->_rate as $key => $value) {
  36. $tmpArr[$key + 1] = $value * 100;
  37. }
  38. //将概率乘十后累计,以便随机选择,组合成
  39. $tmpArr[0] = 0;
  40. foreach ($tmpArr as $key => $value) {
  41. if ($key > 0) {
  42. $tmpArr[$key] += $tmpArr[$key - 1];
  43. }
  44. }
  45. for ($i = 1; $i if ($tmpArr[$i - 1] return $i; //返回中奖的项数(按概率的设置顺序)
  46. }
  47. }
  48. }
  49. }
  50. $rate = array(33, 20, 2, 0.95, 12, 4.55);
  51. $a = new Lottery;
  52. $a->setRate($rate);
  53. for ($i = 0; $i $b = $a->runOnce();
  54. @$rewards[$b]++;
  55. }
  56. unset($rewards['']);
  57. echo array_sum($rewards);
  58. ?>
  59. 运行10000次,对比设置概率和中奖次数
  60. 设置概率 中奖次数
    %
    %
    %
    %
    %
    %
复制代码
一个抽奖函数(自定义中奖项数和概率)