Skip to content

Instantly share code, notes, and snippets.

@Dangeranger
Last active June 18, 2021 17:25
Show Gist options
  • Save Dangeranger/ccc32bf87f38a7a99728b12e21f74160 to your computer and use it in GitHub Desktop.
Save Dangeranger/ccc32bf87f38a7a99728b12e21f74160 to your computer and use it in GitHub Desktop.
A detailed explanation of the function "randomInteger" using comments
/*
* Function randomInteger:
*
* Accepts two numbers, and returns a random integer
* between the min and max inclusive of both numbers
*
* Example Usage:
* randomInteger(1, 10) => 7
* randomInteger(1, 10) => 3
* randomInteger(1, 10) => 9
* randomInteger(50, 75) => 67
* randomInteger(50, 75) => 92
* randomInteger(50, 75) => 71
*/
function randomInteger(min, max) {
// make the range variable equal the
// the difference between the max
// and the min, plus 1
let range = max - min + 1;
console.log("The range of the random number is: ", range);
// create a floating point number that is between
// the difference of the min and the max, this float
// will need to be added to the min, so that it is at
// least the min number or larger
let randomFloatWithinRange = Math.random() * range;
console.log("The random floating point number is: ", randomFloatWithinRange);
// find the neaerst integer, whole number, that is smaller
// than the calculated floating point number
let nearestIntegerDown = Math.floor(randomFloatWithinRange);
console.log("The nearest integer less than the floating point number is: ", nearestIntegerDown);
// add the min number to the nearestIntegerDown so that the
// result of the function is at least as large as the min
// and up to the size of the max
let finalResult = min + nearestIntegerDown;
console.log("The final result is: ", finalResult);
return finalResult;
}
console.log(randomInteger(1, 10));
console.log(randomInteger(1, 10));
console.log(randomInteger(50, 75));
console.log(randomInteger(50, 75));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment