function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min);
}
const rndInt = randomIntFromInterval(1, 6);
console.log(rndInt);
What it does "extra" is it allows random intervals that do not start with 1. So you can get a random number from 10 to 15 for example. Flexibility.
Answer from Francisc on Stack Overflowfunction randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min);
}
const rndInt = randomIntFromInterval(1, 6);
console.log(rndInt);
What it does "extra" is it allows random intervals that do not start with 1. So you can get a random number from 10 to 15 for example. Flexibility.
Important
The following code works only if the minimum value is `1`. It does not work for minimum values other than `1`.If you wanted to get a random integer between 1 (and only 1) and 6, you would calculate:
const rndInt = Math.floor(Math.random() * 6) + 1
console.log(rndInt)
Where:
- 1 is the start number
- 6 is the number of possible results (1 + start (6) - end (1))
Generate A Random Number Within A Range - How Does the Math Work?
Basic JavaScript - Generate Random Whole Numbers with JavaScript
Random Number Generation
Get a number between 1 and 10 with math.random
What is the default range of numbers generated by Math.random() in JavaScript?
Why can’t I set a seed for Math.random() in JavaScript?
How do I create a random string of characters in JavaScript?
Videos
Hi all,
I'm learning JS through FCC and it's going okay so far. I'm not a very mathematically inclined person, however, so I struggle with some concepts.
I'm struggling to understand how the following code works;
Math.floor(Math.random() * (max - min + 1)) + min
I tried writing out an example on paper and used 10 and 5 as max and min respectively.
Math.floor(Math.random() * (10 - 5 + 1)) + 5
wouldn't this mean that I can get numbers higher than the max though? Say I get a randomly generated 0.99; well 0.99 * (6) + 5 = 10.94 which is greater than my max of 10?
Am I doing this wrong?