当前位置:首页 > 叨叨念念 > PHP简单权重算法事例

PHP简单权重算法事例

叨叨念念 / 星之宇 / 2024-8-6 10:04 / 浏览:145 / 评论:0

PHP从二维数组中根据权重随机取出一个元素,权重越高取出的概率越高,抽奖的简单算法。


二维数组数据如下,weight代表权重大小

$data = [
    ['id'=>1,'name'=>'特等奖','weight'=>1],
    ['id'=>2,'name'=>'一等奖','weight'=>3],
    ['id'=>3,'name'=>'二等奖','weight'=>5],
    ['id'=>4,'name'=>'三等奖','weight'=>10],
    ['id'=>5,'name'=>'四等奖','weight'=>20],
    ['id'=>6,'name'=>'五等奖','weight'=>30],
    ['id'=>7,'name'=>'谢谢抽奖','weight'=>100]
];


方法一:按照权重生成一个数组,数组随机取值即可。

function weight(array $data){
    $res = $tmp = array();
    $weight = 0;
    if(!empty($data)){
        foreach($data as $v){
            $weight += $v['weight'];
            for ($i = 0; $i < $v['weight']; $i++) {
                $tmp[] = $v;
            }
        }
        $res = $tmp[array_rand($tmp,1)];
    }
    return $res;
}
上述代码可以简单的实现权重随机取值,但是如果weight值也很大的时候,上述程序运行速度影响很大。


方法二:把二维数组的元素根据权重看成1个线段,根据总线段取出随机1个值判断在哪个线段上即可。

function weight(array $data){
    $res = array();
    $rand = rand(1,array_sum(array_column($data,'weight')));
    if(!empty($data)){
        $weight = 0;
        foreach($data as $v){
            $weight += $v['weight'];
            if($weight>=$rand){
                $res = $v;
                break;
            }
        }
    }
    return $res;
}

上述代码解决了weight值太大导致程序运行时间太长问题。在上述二种方法中通过100次取值测试,方法二要比方法一快4倍以上。所以建议选择方法二

目前有 0 条评论

    • 昵称
    • 邮箱
    • 网址