I am trying to set up a random number picker 1 through 5, with each number showing up on a predefined percentage value; 1 showing up often and 5 showing up the least often. So for example, the chances if these 5 numbers showing up might be as follows: 1 – 45%, 2 – 25%, 3 – 15%, 4 – 10%, 5 – 5%. I have tried a few approaches (one seen below I know its totally wrong) with out any luck. Does anyone have any ideas how to efficiently approach this?
$rand = rand(1,1000);
if ($rand <= 275) {
$rand_num = 1;
} else if ($rand > 275 && $rand <= 525) {
$rand_num = 2;
} else if ($rand > 525 && $rand <= 750) {
$rand_num = 3;
} else if ($rand > 750 && $rand <= 925) {
$rand_num = 4;
} else {
$rand_num = 5;
}
>Solution :
One of the ways — just use conditions to split the random result:
To keep it simple, set the random numbers to be between 1 and 100
1 – 45%, 2 – 25%, 3 – 15%, 4 – 10%, 5 – 5%.
The code will be:
$rand = rand(1,100);
if ($rand <=45) {
$rand_num = 1;
}
if ($rand >45 && $rand <=70) {
$rand_num = 2;
}
if ($rand >70 && $rand <=85) {
$rand_num = 3;
}
if ($rand >85 && $rand <=95) {
$rand_num = 4;
}
if ($rand >95) {
$rand_num = 5;
}