Home  >  Article  >  Backend Development  >  PHP random lottery code analysis based on prize percentage_PHP tutorial

PHP random lottery code analysis based on prize percentage_PHP tutorial

WBOY
WBOYOriginal
2016-07-14 10:11:571289browse

/**
 * 概率算法
 * @param array $probability
 * @return integer|string
 */
function get_rand($probability) {
    // 概率数组的总概率精度
    $max = array_sum($probability);
    foreach ($probability as $key => $val) {
        $rand_number = mt_rand(1, $max);//从1到max中随机一个值

        if ($rand_number <= $val) {//如果这个值小于等于当前中奖项的概率,我们就认为已经中奖
            return $key;
        } else {
            $max -= $val;//否则max减去当前中奖项的概率,然后继续参与运算
        }
    }
    /**
     * 综上分析:
     *      确保对每个人获取奖品的概率是一样的
     *      如果某件奖品没了,应该讲概率修改为0
     *      考虑到高并发,在检测到用户中奖后,应该检查一下奖品是否存在,没了就直接返回没中奖或者次一级奖品
     *      最后才将中奖结果返回
     */
}

// 概率比例
/* 接下来我们通过PHP配置奖项。 */
$data = array(
    array(
        "prize" => "平板电脑", "prob" => 1
    ),
    array(
        "prize" => "数码相机", "prob" => 3
    ),
    array(
        "prize" => "音箱设备", "prob" => 5
    ),
    array(
        "prize" => "8G优盘", "prob" => 20
    ),
    array(
        "prize" => "10Q币", "prob" => 200
    ),
    array(
        "prize" => "下次没准就能中噢", "prob" => 771
    )
);

foreach ($data as $key => $val) {
    $probability[$key] = $val["prob"];
}
$n = get_rand($probability);
$res[&#39;yes&#39;] = $data[$n]["prize"];//$res[&#39;yes&#39;] =$data[$n][0];

unset($data[$n]); // 将中奖项从数组中剔除,剩下未中奖项 
shuffle($data); // 将其它奖项顺序打乱

$func = create_function(&#39;$x&#39;, &#39;return $x["prize"];&#39;);

//$res[&#39;no&#39;] = array_map(function($x){return $x[0];}, $data);  // 除了中奖外的其他数据
$res[&#39;no&#39;] = array_map($func, $data);  // 除了中奖外的其他数据

print_r($res);

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477247.htmlTechArticle/*** Probability algorithm * @param array $probability * @return integer|string*/function get_rand($probability) { // Total probability accuracy of probability array$ max = array_sum($probability); foreac...
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