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

How to Efficiently Generate Unique Random Numbers Within a Specific Range?

Patricia Arquette
Release: 2024-12-05 04:55:10
Original
190 people have browsed it

How to Efficiently Generate Unique Random Numbers Within a Specific Range?

Generating Unique Random Numbers within a Range

Question: How can I efficiently generate unique random numbers within a specified range?

Answer:

The provided code generates random numbers within a range but may not guarantee uniqueness. For an optimized solution, consider the following approaches:

1. Array with Random Order:

  • Generate an array of numbers within the range (range(min, max)).
  • Shuffle the array using shuffle().
  • This creates a random order of numbers, which can be sliced to the desired quantity for unique results.

2. Wrapped Function:

  • Encapsulate the array shuffling technique in a function:
function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
    $numbers = range($min, $max);
    shuffle($numbers);
    return array_slice($numbers, 0, $quantity);
}
Copy after login
  • Example usage:
print_r(UniqueRandomNumbersWithinRange(0, 25, 5));
Copy after login

Result:

An array of the specified quantity with unique random numbers within the given range.

The above is the detailed content of How to 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