Generating random results by weight in PHP?

前端 未结 12 730
青春惊慌失措
青春惊慌失措 2020-11-22 07:35

I know how to generate a random number in PHP but lets say I want a random number between 1-10 but I want more 3,4,5\'s then 8,9,10\'s. How is this possible? I would post wh

12条回答
  •  灰色年华
    2020-11-22 08:24

    Plain and fair. Just copy/paste and test it.

    /**
     * Return weighted probability
     * @param (array) prob=>item 
     * @return key
     */
    function weightedRand($stream) {
        $pos = mt_rand(1,array_sum(array_keys($stream)));           
        $em = 0;
        foreach ($stream as $k => $v) {
            $em += $k;
            if ($em >= $pos)
                return $v;
        }
    
    }
    
    $item['30'] = 'I have more chances than everybody :]';
    $item['10'] = 'I have good chances';
    $item['1'] = 'I\'m difficult to appear...';
    
    for ($i = 1; $i <= 10; $i++) {
        echo weightedRand($item).'
    '; }

    Edit: Added missing bracket at the end.

提交回复
热议问题