Saucy - 1 year ago 103
jQuery Question

# Generate random number between 000 to 999, and a single digit can only occur maximum of two times

How can I generate numbers that range from 000 to 999? Also, a single digit can only occur maximum of two times in the same number.

Examples of numbers I'd like to generate:

``````094
359
188
900
004
550
``````

Examples of numbers I don't want to generate:

``````000
999
444
``````

What I've got so far:

``````function randomNumbers () {
var one = Math.floor(Math.random() * 9) + 0;
var two = Math.floor(Math.random() * 9) + 0;
var three = Math.floor(Math.random() * 9) + 0;

return '' + one + two + three;
};
``````

I know the code can be improved a lot, I just don't know how. Current function isn't checking if the same number occurs three times (should only occur a maximum of two).

I can use jQuery in the project.

Answer Source

Here is a solution that will never have to retry. It returns the result in constant time and spreads the probability evenly among the allowed numbers:

``````function randomNumbers () {
var val = Math.floor(Math.random() * 990);
val += Math.floor((val+110)/110);
return ('000' + val).substr(-3);
};

// Test it:
var count = new Array(1000).fill(0);
for (i=0; i<100000; i++) {
count[+randomNumbers()]++;
}
// filter out the counters that remained zero:
count = count.map((v,i) => [i,v]).filter( ([i,v]) => !v ).map( ([i,v]) => i );
console.log('numbers that have not been generated: ', count);``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download