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
Release: 2024-12-14 02:05:09
Original
266 people have browsed it

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.

1

2

$numbers = range(1, 20);

shuffle($numbers);

Copy after login

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.

1

2

3

4

5

function UniqueRandomNumbersWithinRange($min, $max, $quantity) {

    $numbers = range($min, $max);

    shuffle($numbers);

    return array_slice($numbers, 0, $quantity);

}

Copy after login

Example Usage:

1

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

Copy after login

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

Sample Result:

1

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

Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template