PHP generates N non repeating random numbers within the specified range

  • 2021-11-29 23:14:56
  • OfStack

Idea: The generated random numbers are stored in the array, and then the duplicate values are removed in the array, which can generate a fixed number of non-duplicate random numbers.

In the development of PHP website, sometimes we need to generate a fixed number of non-repeating random numbers within the specified range. How to design this function to produce random numbers? We can store randomly generated numbers into an array, but remove duplicate values at the same time of storing, and we can generate a fixed number of non-duplicate random numbers. Of course, you can also store the values in the specified range into an array, and then use shuffle($array) Scramble this array, and then intercept a certain number of values in it. However, the latter method will produce a larger array when the specified random number range is too large.

The code of the first method is given below, and the second method is simpler. You can try it, but it is almost the same


<?php
/*
* array unique_rand( int $min, int $max, int $num )
*  Generate 1 A fixed number of non-repeating random numbers, the number of integers in the specified range must be 
*  Larger than the number of random numbers to be generated 
* $min  And  $max:  Specify the range of random numbers 
* $num:  Specify the build quantity 
*/
function unique_rand($min, $max, $num) {
  $count = 0;
  $return = array();
  while ($count < $num) {
    $return[] = mt_rand($min, $max);
    $return = array_flip(array_flip($return));
    $count = count($return);
  }
  // Scramble the array and assign new subscripts to the array 
  shuffle($return);
  return $return;
}

// Generate 10 A 1 To 100 Non-repeating random numbers in the range 
$arr = unique_rand(1, 100, 10);
echo implode($arr, ",");
?>

The program runs as follows:

48,5,19,36,63,72,82,77,46,16

Add a few explanations:

1. When generating random numbers, we use mt_rand() Function. The average speed of this function to generate random numbers is faster than that of rand() Several times faster.

2. When removing duplicate values in the array, the "flip method" is used, that is, the array_flip() Swap the key and value of the array twice. This method is more efficient than using the array_unique() Much faster.

3. Before returning the array, use the shuffle() Assign a new key name to the array, ensuring that the key name is a continuous number of 0-n. If you don't do this step, you may cause discontinuous key names when deleting duplicate values. If you traverse with for, you will have problems, but if you use foreach or do not need to traverse, you may not need shuffle.

Summarize


Related articles: