Generating random results by weight in PHP?

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

    I just released a class to perform weighted sorting easily.

    It's based on the same algorithm mentioned in Brad's and Allain's answers, and is optimized for speed, unit-tested for uniform distribution, and supports elements of any PHP type.

    Using it is simple. Instantiate it:

    $picker = new Brick\Random\RandomPicker();
    

    Then add elements as an array of weighted values (only if your elements are strings or integers):

    $picker->addElements([
        'foo' => 25,
        'bar' => 50,
        'baz' => 100
    ]);
    

    Or use individual calls to addElement(). This method supports any kind of PHP values as elements (strings, numbers, objects, ...), as opposed to the array approach:

    $picker->addElement($object1, $weight1);
    $picker->addElement($object2, $weight2);
    

    Then get a random element:

    $element = $picker->getRandomElement();
    

    The probability of getting one of the elements depends on its associated weight. The only restriction is that weights must be integers.

提交回复
热议问题