Generate Random Number between Two Numbers
This tutorial shows a snippet for generating random number between two given numbers.
Pseudo-code
max = 5
min = 1
randomNumber = Math.floor( Math.random() * (max - min + 1) + min )
print(randomNumber) // could print numbers in range from 1 to 5
// Math.random generates random floating point number in range from 0 to 1
// Math.floor removes the floating point from the multiplication between (Math.random() * (max - min + 1) + min)
JavaScript Syntax
let max = 5;
let min = 1;
let randomNumber = Math.floor( Math.random() * (max - min + 1) + min );
console.log(randomNumber);
/*
* Output
* COULD print: 1
* ----------to------------
* COULD print: 5
*/
the same code wrapped inside a function looks like
// Function that prints random number between min and max
function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
let random = randomNumber(5, 10);
console.log(random);
/*
* Output
* COULD print: 5
* ----------to------------
* COULD print: 10
*/