0

I use this normally.

var min = 0;
var max = 1;

console.log(Math.round((Math.random() * (max - min) + min)));

It works fine and dandy, but I can't get over thinking that this may be an expensive way of producing this result, does anyone know of a more efficient way?

Or is this the most efficient way?

basickarl
  • 37,187
  • 64
  • 214
  • 335

2 Answers2

0

Hey you can try this approach also

Math.floor(Math.random() * max) + min

This will work efficiently.

Gaurav Mamidwar
  • 338
  • 1
  • 12
0

That's pretty much as efficient as it gets.

You could create a function which will at least clean up your code a bit:

Taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

// Returns a random integer between min (included) and max (excluded)
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}