Jake Ball
Jake Ball

Reputation: 808

Generate a random number with bias result in PHP

I am currently in the process of coding a points system for a website I maintain, and with that I would like to award my users a random amount of points daily.

This is what I am thinking

[0-25] has a 75% chance 
[26 - 51] has a 13% chance
[52 - 76] has a 6% chance
[77 - 115] has a 4% chance
[115 - 200 ] has a mere 2% chance

So, the point bracket 0-25 has the 75% chance of being generated, so is most likely to be the one that is made.

If anyone has any ideas, or suggestions, it would be awesome to hear them.

So, basically I want a random number generated, 1-200 and I want 0-25 to have a much higher chance that 115-200.

Upvotes: 2

Views: 1127

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324840

First generate a random number between 0 and 99. Then generate a second random number in the range picked by the first.

$ranges = Array(
    Array(0,25,75), // [0-25] on 75% chance
    Array(26,51,13),
    Array(52,76,6),
    Array(77,115,4),
    Array(115,200,2)
);
$sel = rand(0,99);
do {
    $pick = array_shift($ranges);
    $sel -= $pick[2];
} while($pick && $sel >= 0);
$random = rand($pick[0],$pick[1]);

Upvotes: 4

Related Questions