How to Generate Random numbers in Javascript based on the provided range Minimum and Maximum characters

安稳与你 提交于 2021-02-05 08:22:09

问题


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:


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))



回答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; }



回答3:


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.




回答4:


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.




回答5:


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-._~()'!*:@,;";


来源:https://stackoverflow.com/questions/62468165/how-to-generate-random-numbers-in-javascript-based-on-the-provided-range-minimum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!