Generate random numbers with fix probability

后端 未结 4 1449
萌比男神i
萌比男神i 2021-01-01 03:15

I red a lot in the forum about this, but all answers were so specific to the the asked question. The nearest one I found to my need was:Probability Random Number Generator b

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-01 03:49

    A quite simple approach would be to have an array with the length 100, writing your "faces" numbers in it, shuffle it and get the first element.

    So for your example in that array are 40x 1, 10x 2, 25x 3.

    Little code example (not tested):

    $probabilities = array(
        1 => 40,
        2 => 10,
        3 => 25,
        4 => 5,
        5 => 10,
        6 => 10
    );
    
    $random = array();
    foreach($probabilities as $key => $value) {
        for($i = 0; $i < $value; $i++) {
            $random[] = $key;
        }
    }
    
    shuffle($random);
    echo $random[0];
    

提交回复
热议问题