码迷,mamicode.com
首页 > 编程语言 > 详细

抽奖权重算法

时间:2020-12-01 12:26:55      阅读:6      评论:0      收藏:0      [点我收藏+]

标签:fun   UNC   data   cal   function   and   rate   dom   code   

算法实现

public function caleResult()
{
    $data = [
        [‘id‘ => 1, ‘name‘ => ‘一等奖‘, ‘weight‘ => 5],
        [‘id‘ => 2, ‘name‘ => ‘二等奖‘, ‘weight‘ => 10],
        [‘id‘ => 3, ‘name‘ => ‘三等奖‘, ‘weight‘ => 25],
        [‘id‘ => 4, ‘name‘ => ‘四等奖‘, ‘weight‘ => 60],
    ];

    //计算总权重
    $total = 0;
    foreach ($data as $val) {
        $total += $val[‘weight‘];
    }

    $rate   = 0;
    $result = [];
    $random = mt_rand(1, $total);
    foreach ($data as $val) {
        $rate += $val[‘weight‘];
        if ($random > $rate) {
            continue;
        }
        $result = $val;
    }
    return $result;
}

抽奖权重算法

标签:fun   UNC   data   cal   function   and   rate   dom   code   

原文地址:https://www.cnblogs.com/jansang/p/14044220.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!