Hi I would like to generate a random number between -x and x in JavaScript. This is what I have :
function randomInt(nb){
let absoluteVal = Math.ceil(Math.random()*nb)
let sign = Math.floor(Math.random()*2)
return sign == 1 ? absoluteVal*(-1) : absoluteVal;
}
console.log(randomInt(4))
It works but it is rather inelegant. I was wondering if somebody knew a better solution. Thanks in advance.
For example with n = 4, it generates this values:
-4 -3 -2 -1 0 1 2 3 4
In total 9 elements. By using positive values, it generates 0 ... 8 with an offset of -4.
function randomInt(n) {
return Math.floor(Math.random() * (2 * n + 1)) - n;
}
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Using Math.random() (returns a random number between 0 and 1) allows you to do it ( using Math.ceil() is used to rounds a number up to the next largest integer)
function randomInt(nb){
return Math.ceil(Math.random() * nb) * (Math.round(Math.random()) ? 1 : -1)
}
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
console.log(randomInt(4));
More about Math.ceil() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil
More about Math.random() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random