概率中奖

<?php
    /**
     * [gailv description]
     * @param array $data
     * @return int $result 正确返回中奖ID 错误就返回0
     */
    function probability($data)
    {
        if (!is_array($data) || empty($data)) {
            return 0;
        }

        $result = 0;

        //概率和
        $probabilitySum = array_sum($data);

        foreach ($data as $key => $value) {
            $rand = mt_rand(1, $probabilitySum);
            if ($rand <= $value) {
                $result = $key;
            }else{
                $probabilitySum -= $value;
            }
        }

        return $result;
    }

    $data = array(
        1 => 10,
        2 => 30,
        3 => 40,
        4 => 90,
        10 => 100
    );

    var_dump(probability($data));


    

 

posted @ 2017-02-23 10:28  天道酬勤,坚持!  阅读(222)  评论(0编辑  收藏  举报