You have four results with given probabilities:
- 0.1% chance to win $ 500.
- 1% chance to win $ 500.
- 10% chance to win $ 500.
The fourth result - without a win - is 100% minus the sum of the other three results, namely 88.9%.
Marc Gabriel explained why your source code was disabled: by encouraging 10% of people who won winners of $ 10 to $ 50, you take them out of a pool of $ 10, which will be only 9% of all people.
Pham Trung contributed to a solution that still attracts winners of higher amounts from the non-winners pool and adjusts the probabilities. This is an acceptable solution, but the easiest solution is in my turn to call the random number generator only once.
This decision also reflects the best analogy with tickets: you place 10,000 tickets in a box. 1000 tickets from 1 to 1000 win 10 dollars. 100 tickets from 1,001 to 1,100 win $ 50. Ten tickets from 1101 to 1110 won $ 500. All 8890 tickets from 1111 win nothing:
function lottery() { var pick = Math.floor(10000 * Math.random()); // random number in the range [0, 10000). if (pick < 1000) return 10; if (pick < 1100) return 50; if (pick < 1110) return 500; return 0; }
In this code, tickets have only the number written on them. You pick one. Then you check to see if the ticket number is $ 10. If not, you are checking the same ticket for a $ 50 bet. There is really only one random action.
(I used the zero-based random number function in Javascript instead of PHP mt_rand , but I think the solution is clear.)
source share