Generate Random Weighted value

前端 未结 6 1421
隐瞒了意图╮
隐瞒了意图╮ 2020-12-28 10:19

Edit: I\'ve rewritten the question in hopes that the goal is a little clearer.

This is an extended question to this question here, and I really like

6条回答
  •  攒了一身酷
    2020-12-28 10:32

    I haven't tried it, but I think this might work:

    $random($probability)
    {
        $rnd = rand() / getrandmax();
    
        foreach($probability as $num => $prob)
        {
            $rnd -= $prob;
            if($rnd <=0)
                return $num;
        }
    
        return -1; //this should never happen
    }
    

    And call it like this (using your second example):

    $distribution = array(
        1 => 0.10,
        2 => 0.15,
        3 => 0.30,
        4 => 0.27,
        5 => 0.14,
        6 => 0.04);
    
    $number = random($distribution);
    

提交回复
热议问题