Home  >  Article  >  php教程  >  php抽奖概率计算类

php抽奖概率计算类

PHP中文网
PHP中文网Original
2016-05-23 17:09:351382browse

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[&#39;num&#39;];
            }
        }
    }

    function addData($name, $chance){
        $this->data[]=array(&#39;name&#39;=>$name, &#39;num&#39;=>$chance);
        $this->chance_count += $chance;
    }

    function getOne(){
        $index = rand(0, $this->chance_count);
        foreach($this->data as $d){
            $index = $index-$d[&#39;num&#39;];
            if($index<=0){
                return $d[&#39;name&#39;];
            }
        }
        return &#39;&#39;;
    }
}


/**
 * 使用示例
 */
$pro=new Probability();
$pro->addData(&#39;iphone&#39;,10);
$pro->addData(&#39;watch&#39;,30);
$pro->addData(&#39;$18&#39;,50);
$pro->addData(&#39;thank you&#39;,10);
$pro->addData(&#39;super big&#39;,1);
for($i=0;$i<100;$i++){
    echo $pro->getOne()."\n";
}

 以上就是php抽奖概率计算类的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:微信开发代码Next article:用php实现评委评分器