Reputation: 2498
I need a function that generates a completely random integer (very important) within a user specified number range (between -9999 to 9999) and a user specified digit limit (between 1 and 4 digits).
Example 1: If the user wants a number between -9999 and 9999 that's 4 digits, the following numbers would be eligible choices -9999 to -1000 and 1000 to 9999.
Example 2: If the user wants a number between 25 and 200 that's 2 OR 3 digits, the following numbers would be eligible choices 25 to 200.
I wrote a function that works but I am not sure if it's the best solution? There's duplicate code and I don't think it's completely random?
// Generates a random integer
// Number range
// Min (-9999-9999)
// Max (-9999-9999)
// Digit limit
// Min (1-4)
// Max (1-4)
function generateRandomInteger(minNumber, maxNumber, minDigits, maxDigits) {
// Generate a random integer in the number range
var num = Math.floor(Math.random() * (maxNumber - minNumber)) + minNumber;
// Find number of digits
var n = num.toString();
n = n.length;
// If number is negative subtract 1 from length because of "-" sign
if (num < 0) {
n--;
}
// End: find number of digits
while ((n > maxDigits) || (n < minDigits)) {
// Generate a random integer in the number range
num = Math.floor(Math.random() * (maxNumber - minNumber)) + minNumber;
// Find number of digits
var n = num.toString();
n = n.length;
// If number is negative subtract 1 from length because of "-" sign
if (num < 0) {
n--;
}
// End: find number of digits
}
return num;
}
Upvotes: 2
Views: 1880
Reputation: 94141
Try this functional approach, it creates an array and shuffles it randomly so it gives "very random" results. I've used it before with very satisfying results.
function getLen( v ) {
return Math.abs( v ).toString().length;
};
function randomInteger( min, max ) {
return ( new Array( ++max - min ) )
.join('.').split('.')
.map(function( v,i ){ return [ Math.random(), min + i ] })
.filter(function( v ){ return getLen( v[1] ) >= getLen( min ) })
.sort().map(function( v ) { return v[1] }).pop();
}
Upvotes: 1
Reputation: 150080
Well here's a version of your function that still uses exactly the same method (i.e., keeps generating numbers until it gets one with the right number of digits), but with the code duplication eliminated:
function generateRandomInteger(minNumber, maxNumber, minDigits, maxDigits) {
var num, digits;
do {
num = Math.floor(Math.random() * (maxNumber - minNumber)) + minNumber;
digits = Math.abs(num).toString().length;
} while (digits > maxDigits || digits < minDigits);
return num;
}
As for your concern about whether this is really random, the Math.random()
method will give you a "pseudo-random" number, but at least you know it will work in all current browsers.
Upvotes: 1