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