2

I have a bit weird requirement where I need to generate Random numbers of the length that is given by user. User can give Minimum Length and the Maximum Length and I need to generate the random numbers which consist of the character length between this range.

For example if the Minimum Length is 6 and Maximum Length is 10 then I need to generate the random numbers whose number of characters has to be between the range 6 and 10. For this example following can be the random generators:

123456,
7654321,
12345678,
987654321,
5432109876, etc.

Like this the Random generators has to contain the length which is between the provided inputs.

I know how to create random numbers between a range and based on fixed character length but I don't know how to created based on variable length. I tried finding the answers but most of them are based on the fixed length and fixed range, could not find the exact match that I am looking for.

It would be really great if someone can help me with this.

1
  • I'd go by randomizing first the lenght between the min and max lengths provided, then getting a random between the min number you can have with that length and the max number you can get with that length Commented Jun 19, 2020 at 10:29

5 Answers 5

3

You may produce an array (Array.from() of randomly chosen length in the range of minLen and maxLen) and populate that with random digits in the range 1 through 9, then Array.prototype.join() the array into string and convert to number:

const randomNum = (minLen, maxLen) => 
                    +Array
                      .from(
                        {length: 0|Math.random()*(maxLen-minLen+1)+minLen},
                        () => 0|Math.random()*9+1
                      )
                      .join('')
                      
console.log(randomNum(3,7))

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

1 Comment

I am unable to understand all the things happening in the code but its working as expected. If incase I would like to modify this function to generate Alphanumeric random numbers then how can I modify it?
2

You could generate the range and get the random values from that range.

For example

min = 2
max = 4

rangeMin = 10
rangeMax = 10000

const
    getRandom = (min, max) => Math.floor(Math.random() * (max - min)) + min,
    getRandomX = (min, max) => getRandom(10 ** (min - 1), 10 ** max);

let min = Infinity,
    max = -Infinity;

for (let i = 0; i < 1e6; i++) {
    let r = getRandomX(6, 10);
    if (min > r) min = r;
    if (max < r) max = r;
}

console.log(min, max);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

Other solutions generate randoms for each digit and join them together to form a number. This is unnecessary. We know that a number with at least m-th digits is at least 10m - 1. Similarly, having at most n digits means that the number is smaller than 10n.

const randomWithinRange = (min, max) => Math.floor(Math.random() * (max - min) + min);
const randomWithMagnitude = (min, max) => randomWithinRange(Math.pow(10, min - 1), Math.pow(10, max));

const arr = Array(100000).fill().map(() => randomWithMagnitude(6, 10)).sort((a, b) => a - b);
console.log(arr.slice(0, 100).join(", "));
console.log(arr.slice(99900, 100000).join(", "));

Note: I've sorted the 100.000-sized array just to show you the smallest and largest numbers generated.

Comments

0

Try this:

var minLength = 6;
var maxLength = 10;
var generatedNumbers = [];
for(var i=minLength ; i<=maxLength; i++){
   var num = "";    
   for(var j=1;j<=i;j++){
       num = num + Math.floor(Math.random(10) * 10);   
   }
   generatedNumbers.push(num);
}
console.log(generatedNumbers);

Edit

var minLength = 1;
var maxLength = randomNumber;
var generatedNumbers = [];
for(var i=minLength ; i<=maxLength; i++){
   var num = "";    
   for(var j=1;j<=i;j++){
       num = num + Math.floor(Math.random(10) * 10);   
   }
   generatedNumbers.push(num);
}
console.log(generatedNumbers);

this will help.

1 Comment

Thanks for the response. But seems like this is generating first 6 then 7 then 8 characters random numbers. I am trying to create the random numbers when the length of the random number is also pretty much random like it can be 6 digit then 9 digit then 7 digit so on, Is there a way we can modify this?
-1

Thanks a lot, everyone for the answer. Here is the approach that I have used.

If the random numbers with just Numeric is required:

var charset         = "0123456789";
var max_Length      = 5;
var min_Length      = 10;
var charPicker      = Math.floor(Math.random() * (max_Length - min_Length + 1) + min_Length);
var randomId;
for (var i = 0; i < charPicker; i++)
{
    randomId += charset.charAt(Math.floor(Math.random() * charset.length));
}
console.log(randomId);

Change the character set for Alphanumeric and Alphanumeric with URL specific characters like this:

var charset         = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var charset         = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~()'!*:@,;";

Comments

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.