Home >Backend Development >PHP Tutorial >How Can I Efficiently Generate Unique Random Numbers Within a Specific Range?

How Can I Efficiently Generate Unique Random Numbers Within a Specific Range?

Barbara Streisand
Barbara StreisandOriginal
2024-12-14 02:05:09261browse

How Can I Efficiently Generate Unique Random Numbers Within a Specific Range?

Generating Unique Random Numbers within a Range: Optimized Approach

To generate unique random numbers within a specified range, consider the following improved methods:

Array with Shuffled Order:

  • Create an array with numbers within the desired range.
  • Use shuffle() to randomize the order of the array elements.
$numbers = range(1, 20);
shuffle($numbers);

Wrapped Function:

  • Define a function that encapsulates the logic for generating a specified number of unique random numbers within a range.
  • Within the function, create an array with the desired range, shuffle its order, and return a slice of the array containing the desired number of elements.
function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
    $numbers = range($min, $max);
    shuffle($numbers);
    return array_slice($numbers, 0, $quantity);
}

Example Usage:

$result = UniqueRandomNumbersWithinRange(0, 25, 5);

This will generate and return an array of 5 unique randomly ordered numbers within the range 0-25.

Sample Result:

$result = [14, 16, 17, 20, 1]

The above is the detailed content of How Can I Efficiently Generate Unique Random Numbers Within a Specific Range?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn