Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Choose Random Number With Weights

Assume I want to choose a number from 1-10 at random, but there are weights to each number.

1 - 15% chance
2 - 15% chance
3 - 12% chance
4 - 12% chance
5 - 10% chance
6 - 10% chance
7 - 8% chance
8 - 8% chance
9 - 5% chance
10 - 5% chance

How would I go about coding this up in PHP?

like image 613
Justin Avatar asked May 02 '26 09:05

Justin


1 Answers

I assume your percentages add up to 100%?

Build an array with

15 times a '1' value, 
15 times a '2' value, 
... 
10 times a '6' value, 
8 times a '7' value,
...
5 times 1 '10' value

You'll end up with a single array which contains 100 elements.

Pick an element randomly (and pop it from the array).

like image 107
ChristopheD Avatar answered May 04 '26 22:05

ChristopheD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!