2

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;
}
1
  • "completely random integer (very important)". FYI Math.random is nowhere near "completely random". If you want random, use crypto.getRandomValues. Commented Nov 14, 2012 at 6:11

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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();
}

5 Comments

Check demo, it works with negative and positive numbers. jsbin.com/awanib/2/edit
+1. I've deleted my previous comments because I answered my own questions by looking at your code more carefully. I do have a question though: would it be more efficient to change the first .map() to return [Math.random(), min+i], thus eliminating the second .map() (with the .filter() changed to match)?
You're right. I just quickly modified this other script of mine where the requirements are a bit different.
Cool. Note that the user might request a minimum number of digits that is less than the length of the minimum value, e.g., -1000 to +1000 with 3 to 4 digits
Right... so I guess it should be >= for range such as -99|150... Maybe it does not fulfill OPs needs tho.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.