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))
Videos
What You really want to do is to get [1, 2, 3] array and shuffle it. I would do it like this:
const numbers = [];
const shuffled = [];
// prepare array of sorted numbers [1, 2, 3]
for(let i=0; i<scoreDisplay.length; i++)
numbers.push(i + 1);
// shuffle the array by picking random position in sorted array and moving it to result array
while (numbers.length > 0)
shuffled.push(numbers.splice(Math.floor(Math.random() * numbers.length), 1)[0]);
// print result
for(let i=0; i<scoreDisplay.length; i++)
scoreDisplay[i].textContent = shuffled[i];
As you want to generate only three random numbers and should not be colliding, why can't you use shuffle an array with 3 numbers in it var arr = [1,2,3];
each time player clicks start game, the array shuffles.
Shuffling array - >> How to randomize (shuffle) a JavaScript array?
Thanks
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?