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
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?
you need to get a new number and compare with the old one, if it's the same one, get a new one and repeat. a little recursuion could help here!
let lastNumber // start with undefined lastNumber
function getRandNumber() {
var x = Math.floor((Math.random() * 5) + 1); // get new random number
if (x === lastNumber) { // compare with last number
return getRandNumber() // if they are the same, call the function again to repeat the process
}
return x // if they're not the same, return it
}
function myFunction() {
const number = getRandNumber()
lastNumber = number
document.getElementById("demo").innerHTML = number;
}
How about creating a list to pick from with the last number removed?
lastNumber = 0; // Initialize it to a number outside the list so first pick is from full five.
sourceList = [1,2,3,4,5];
function noRepeatRandom(){
nextList = sourceList.filter(function(x){return x!=lastNumber});
randomIndex = Math.floor(Math.random() * nextList.length);
lastNumber = nextList[randomIndex]
return lastNumber
}
This should pick from the full five for the first call.