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))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
It works but it is rather inelegant. I was wondering if somebody knew a better solution. Thanks in advance.
CodePudding user response:
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 ofset 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; }
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Using Math.random()
(returns a random number between 0 and 1) allows you to do it.
function randomInt(nb){
return Math.ceil(Math.random() * nb) * (Math.round(Math.random()) ? 1 : -1)
}
console.log(randomInt(4));
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>