Skip to content

Instantly share code, notes, and snippets.

@padolsey
Created November 15, 2009 21:55
Show Gist options
  • Select an option

  • Save padolsey/235501 to your computer and use it in GitHub Desktop.

Select an option

Save padolsey/235501 to your computer and use it in GitHub Desktop.
/**
* Random number generator, never returns the same number
* more than once, only returns integers.
* @param min minimum number, inclusive
* @param max maximum number, inclusive
* Both @params are optional
*/
var generateRandomNumber = (function(){
var used = {};
return function(min, max) {
min = min || 0;
max = max || 9999999;
var i, attempts = 0;
while ( used[i = Math.floor(Math.random() * (max - min + 1) + min)] ) {
if ( attempts++ > max-min ) {
return null;
}
}
used[i] = true;
return i;
};
})();
// E.g.
generateRandomNumber(0, 2); // 0
generateRandomNumber(0, 2); // 2
generateRandomNumber(0, 2); // 1
generateRandomNumber(0, 2); // null
/////////////////////////////////////////////
// Another version, that can be instantiated:
/////////////////////////////////////////////
var RandomNumberGen = (function(){
function RandomNumberGen(min, max) {
this.used = {};
this.min = min || 0;
this.max = max || 9999999;
}
RandomNumberGen.prototype.gen = function() {
var i, attempts = 0,
max = this.max,
min = this.min,
used = this.used;
while ( used[i = Math.floor(Math.random() * (max - min + 1) + min)] ) {
if ( attempts++ > max-min ) {
return null;
}
}
used[i] = true;
return i;
};
return RandomNumberGen;
})();
// E.g.
var myGen = new RandomNumberGen(0, 2);
myGen.gen(); // 0
myGen.gen(); // 2
myGen.gen(); // 1
myGen.gen(); // null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment