Nick
Nick

Reputation: 6346

Random number between x and y excluding a range of numbers inbetween

I am implementing a system at the moment where it needs to allocate a number in a certain range to a person, but not use any number that has been used before.
Keep in mind, both the number range and exclusion list are both going to be quite large.

Initially, I thought doing something like this would be best:

<?php 
  $start = 1;
  $end = 199999;
  $excluded = array(4,6,7,8,9,34);
  $found = FALSE;
  while (!$found) {
    $rand = mt_rand($start,$end);
    if (!in_array($rand,$excluded)) {
      $found = TRUE;
    }
  } 
?>

But I don't think this is ideal, there is the possibility of an infinite loop (or it taking a very long time / timing out the script).

I also thought about generating an array of all the numbers I needed, but surely a massive array would be worse? Also doing an array diff on 2 massive arrays would surely take a long time too? Something like this:

<?php 
  $start = 1;
  $end = 199999;
  $allnums = range($start,$end);
  $excluded = array(4,6,7,8,9,34);
  $searcharray = array_diff($allnums,$excluded);
  $rand = array_rand($searcharray);
?>

So, my question would be which would be a better option? And is there another (better) way of doing this that someone has used before?

Upvotes: 1

Views: 753

Answers (1)

fire
fire

Reputation: 21531

Array's holding large amounts of data will use up a lot of memory, can you not use a database to hold these numbers in? That's generally what they are designed for.

Upvotes: 2

Related Questions