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

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

Susan Sarandon
Release: 2024-12-07 08:54:12
Original
579 people have browsed it

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

Generating Unique Random Numbers within a Range

Generating a list of unique random numbers within a specified range can be a challenging task. One approach is to generate random numbers and check if they are unique each time. However, this method can be inefficient for large ranges or a large number of random numbers.

A more optimized approach is to create an array of numbers within the desired range and then shuffle the array to randomize the order. The resulting array will contain unique random numbers within the specified range.

Using an Array with Range of Numbers at Random Order:

$numbers = range(1, 20);
shuffle($numbers);
Copy after login

In this code, range(1, 20) creates an array of numbers from 1 to 20. The shuffle() function then randomizes the order of the numbers in the array. This method is particularly useful when the number of random numbers needed is less than or equal to the range of numbers.

Using a Wrapped Function:

For more complex scenarios, you can create a wrapped function that takes the minimum value, maximum value, and the desired quantity of random numbers as input:

function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
    $numbers = range($min, $max);
    shuffle($numbers);
    return array_slice($numbers, 0, $quantity);
}
Copy after login

This function takes the initial range of numbers, shuffles them, and then uses array_slice() to extract the desired number of random numbers.

Example Usage:

The following code demonstrates how to use the UniqueRandomNumbersWithinRange() function:

<?php
print_r(UniqueRandomNumbersWithinRange(0, 25, 5));
?>
Copy after login

Result:

Array
(
    [0] => 14
    [1] => 16
    [2] => 17
    [3] => 20
    [4] => 1
)
Copy after login

This code generates an array of 5 unique random numbers between 0 and 25. The numbers are shuffled to ensure uniqueness.

The above is the detailed content of How Can I Efficiently Generate a List of 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