Weighted random selection from array

后端 未结 13 1920
醉酒成梦
醉酒成梦 2020-11-28 03:13

I would like to randomly select one element from an array, but each element has a known probability of selection.

All chances together (within the array) sums to 1.<

13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 03:20

    This is a PHP code I used in production:

    /**
     * @return \App\Models\CdnServer
    */
    protected function selectWeightedServer(Collection $servers)
    {
        if ($servers->count() == 1) {
            return $servers->first();
        }
    
        $totalWeight = 0;
    
        foreach ($servers as $server) {
            $totalWeight += $server->getWeight();
        }
    
        // Select a random server using weighted choice
        $randWeight = mt_rand(1, $totalWeight);
        $accWeight = 0;
    
        foreach ($servers as $server) {
            $accWeight += $server->getWeight();
    
            if ($accWeight >= $randWeight) {
                return $server;
            }
        }
    }
    

提交回复
热议问题