Last active
May 8, 2022 07:39
-
-
Save kumarsonsoff3/e817e9b0e9e8e19751093428ab24a734 to your computer and use it in GitHub Desktop.
Generate a Random integer with Recursion
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
| // Normally this could be used for Random number generation | |
| function getRandomArbitrary(min, max) { | |
| return Math.trunc(Math.random() * (max - min) + min); | |
| } | |
| // The idea is to recursive-ise this so that a running total of the number of max hits is stored, combined, and then returned. | |
| // To do this recursively is simple, just call the method from itself: | |
| function generateNumber(max, min) { | |
| let randomNumber = Math.floor(Math.random() * (max - min + 1) + min); | |
| if (randomNumber == max) { | |
| randomNumber += generateNumber(min, max); | |
| } | |
| return randomNumber; | |
| } | |
| // This could be solved without Recursion | |
| function generateNum(min, max) { | |
| var randNumber = 0; | |
| do { | |
| var num = Math.floor(Math.random() * (max - min + 1)) + min; | |
| randNumber += num; | |
| } while (num == max); | |
| return randNumber; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment