Created
December 1, 2023 00:12
-
-
Save hussnainsheikh/e0ece2738ff8870860fb1d2b87300b9e to your computer and use it in GitHub Desktop.
Recursion to generate random numbers within range with no duplicate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** generate an array of random | |
* numbers within given range | |
**/ | |
function generateRandom($end, $total, $start = 0, $numbers = []) | |
{ | |
if(count($numbers) == $total) { | |
return $numbers; | |
} | |
$number = rand($start, $end); | |
if(!in_array($number, $numbers)) { | |
$numbers[] = $number; | |
} | |
return generateRandom($end, $total, $start, $numbers); | |
} | |
generateRandom(50, 7, 11); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment