search
Homephp教程PHP源码php抽奖概率计算类

php抽奖概率计算类

May 23, 2016 pm 05:09 PM

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.