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!