I need to get a random number that is between
0 - 80
and
120 - 200
I can do
$n1 = rand(0, 80);
$n2 = rand(120, 200);
But then I need to choose between n1
and n2
. Cannot do
$n3 = rand($n1, $n2)
as this may give me a number between 80 - 120
which I need to avoid.
How to solve this?
Since both ranges have different sizes (even if only by 1 number), to ensure good random spread, you need to do this:
$random = rand( 0, 200 - 39 );
if ($random>=120-39) $random+=39;
Fastest method. :)
The way this works is by pretending it's a single range, and if it ends up picking a number above the first range, we increase it to fit within the second range. This ensures perfect spread.
Since both ranges have the same size you can simply use rand(0, 1)
to determine which range to use.
$n = rand(0, 1) ? rand(0, 80) : rand(120, 200);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With