Skip to content

Instantly share code, notes, and snippets.

@kumarsonsoff3
Last active May 8, 2022 07:39
Show Gist options
  • Select an option

  • Save kumarsonsoff3/e817e9b0e9e8e19751093428ab24a734 to your computer and use it in GitHub Desktop.

Select an option

Save kumarsonsoff3/e817e9b0e9e8e19751093428ab24a734 to your computer and use it in GitHub Desktop.
Generate a Random integer with Recursion
// 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