Skip to content

Instantly share code, notes, and snippets.

@mmalone
Created November 6, 2015 18:34
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mmalone/d710793137ed0d6b8cb4 to your computer and use it in GitHub Desktop.
Save mmalone/d710793137ed0d6b8cb4 to your computer and use it in GitHub Desktop.
/**
* Unfortunately ECMAScript is not precise enough with its definition of
* Math.random(), so this parameter is implementation dependent. It should
* definitely be a power of two otherwise I'm pretty sure the algorithm below
* breaks while calculating the limit.
*/
var MAX_RANDOM = Math.pow(2, 30);
/**
* CAVEAT: I knocked this together in a couple minutes. It could use some
* review.
*
* Returns a pseudo-random, uniformly distributed integer between 0 (inclusive)
* and the specified value (exclusive).
*/
Math.randomInt = function Math_randomInt(n) {
if (n <= 0 || n > MAX_RANDOM) {
throw new RangeError('Parameter must be between 0 and ' + MAX_RANDOM);
}
var limit = (MAX_RANDOM - (MAX_RANDOM % n)) / MAX_RANDOM;
var rand = Math.random();
while (rand >= limit) {
rand = Math.random();
}
return Math.floor(rand * n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment