抽奖权重算法

2021-03-14 01:29

阅读:562

标签: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


评论


亲,登录后才可以留言!