Search code examples
phprandomdice

Controlling likelyhood of randomly generated numbers


If I wanted a random number between one and three I could do $n = mt_rand(1,3).

There is a 33% chance that $n = 1, a 33% chance it's 2, and a 33% chance that it's 3.

What if I want to make it more difficult to get a 3 than a 1?

Say I want a 50% chance that a 1 is drawn, a 30% chance that a 2 is drawn and a 20% chance that a 3 is drawn?

I need a scalable solution as the possible range will vary between 1-3 and 1-100, but in general I'd like the lower numbers to be drawn more often than the higher ones.

How can I accomplish this?


Solution

  • This is maths.

    In your example the just chose a random number between 0 and 99.

    Values returned between 0 to 49 - call it 1 Values returned between 50 - 69 - Call it 2 Values returned between 70 - 99 - Call it 3

    Simple if statement will do this or populate an array for the distribution required