View Single Post
Old 11-14-2012, 06:05 AM   PM User | #1
genstonewall
New to the CF scene

 
Join Date: Nov 2012
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
genstonewall is an unknown quantity at this point
JavaScript Function: Generate a random integer within specified range AND digit limit

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? Thanks.

Code:
// 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;
}
genstonewall is offline   Reply With Quote