Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose 1 random number from 2 different number ranges?

Tags:

php

random

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?

like image 566
pepe Avatar asked Apr 22 '12 21:04

pepe


2 Answers

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.

like image 190
DanRedux Avatar answered Sep 25 '22 02:09

DanRedux


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);
like image 43
ThiefMaster Avatar answered Sep 25 '22 02:09

ThiefMaster