Generating random results by weight in PHP?

前端 未结 12 843
青春惊慌失措
青春惊慌失措 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:03

    function getBucketFromWeights($values) { $total = $currentTotal = $bucket = 0;

    foreach ($values as $amount) {
        $total += $amount;
    }
    
    $rand = mt_rand(0, $total-1);
    
    foreach ($values as $amount) {
        $currentTotal += $amount;
    
        if ($rand => $currentTotal) {
            $bucket++;
        }
        else {
            break;
        }
    }
    
    return $bucket;
    

    }

    I ugh modified this from an answer here Picking random element by user defined weights

    After I wrote this I saw someone else had an even more elegant answer. He he he he.

提交回复
热议问题