S
S
SoffTeam2017-01-24 00:06:18
PHP
SoffTeam, 2017-01-24 00:06:18

Random number from multiple ranges?

I am interested in the implementation of the following moment,
for example, we have several numerical ranges
1-17
18-25
26-100
the range 18-25 for some reason fell out
how to implement the search for a random number from several ranges: 1-17, 26-100

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2017-01-24
@SoffTeam

$ranges = ;
$total = 0;
foreach ($ranges as $range)
  $total += $range[1]-$range[0]+1;
$rand = rand(0, $total-1);
foreach ($ranges as $range) {
  $rand += $range[0];
  if ($rand > $range[1])
    $rand -= $range[1]+1;
  else
    break;
}
echo $rand;

S
Sergey, 2017-01-24
@red-barbarian

v = rand(1,100-8)
if v> 17 then v = v+8 you
get a uniform distribution regardless of the length of the ranges

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question