php抽奖概率计算类
程序员文章站
2022-04-08 21:19:48
...
php抽奖概率计算类
<?php /** * 概率计算类 * 可用于抽奖等 */ class Probability { /** * 概率统计数据 * thing => chance */ var $data = array(); var $chance_count = 0; function __construct($initdata = array()){ if(!empty($initdata)){ $this->data = $initdata; foreach($initdata as $d){ $this->chance_count += $d['num']; } } } function addData($name, $chance){ $this->data[]=array('name'=>$name, 'num'=>$chance); $this->chance_count += $chance; } function getOne(){ $index = rand(0, $this->chance_count); foreach($this->data as $d){ $index = $index-$d['num']; if($index<=0){ return $d['name']; } } return ''; } } /** * 使用示例 */ $pro=new Probability(); $pro->addData('iphone',10); $pro->addData('watch',30); $pro->addData('$18',50); $pro->addData('thank you',10); $pro->addData('super big',1); for($i=0;$i<100;$i++){ echo $pro->getOne()."\n"; }
以上就是php抽奖概率计算类的内容,更多相关内容请关注PHP中文网(www.php.cn)!