Hector Gomez
Hector Gomez

Reputation: 33

PHP Weighted random number

How can I generate a weighted random number between 1 and 10 with 10 being the highest chance and 1 being the lowest chance?

rand(1,10) ?

Needs to be a simple one line code since it will be run 100,000's of times

Upvotes: 3

Views: 2107

Answers (2)

yarns
yarns

Reputation: 257

To get a weighted random number you can configure the first three variables to your liking:

$from = 1; // min
$to = 10; // max
$weight = 5;
$param = [$weight, mt_rand($from, $to)];
$result = [mt_rand(min($param), max($param))];

This basically gets a random number between min and max, then another random number between the result and the given weight. The second random number generation simply brings the result closer to the given weight.

test:

$results = [0,0,0,0,0, 0,0,0,0,0,0];
$weight = 5;
for ($i = 0; $i < 1000; $i++)
 {
    $param = [$weight, mt_rand(1, 10)];
    $results[mt_rand(min($param), max($param))]++;
 }
print_r($results);

outputs

Array
(
    [0] => 0
    [1] => 18
    [2] => 45
    [3] => 72
    [4] => 131
    [5] => 377
    [6] => 136
    [7] => 92
    [8] => 69
    [9] => 41
    [10] => 19
)

Upvotes: 0

Webby
Webby

Reputation: 2765

OK I think I understand what you're trying to say..

try this :

mt_rand(mt_rand(1, 10),10 );

I looped it a million times :

10 = 292634 
9 = 193333 
8 = 142815 
7 = 109580 
6 = 84616 
5 = 64498 
4 = 47666 
3 = 33450 
2 = 21286 
1 = 10122 

Upvotes: 15

Related Questions