Reputation: 7734
Update: The number can be started with zero.
I want to have a function like
function getRandomNumber(n){
...
}
I hope it gets a number with n
digits while none of the digits is repeated. For instance:
getRandomNumber(3) -> 152 is what I want.
getRandomNumber(1) -> 6 is what I want.
getRandomNumber(6) -> 021598 is what I want. It can start with zero.
getRandomNumber(5) -> 23156 is what I want.
getRandomNumber(3) -> 252 is not because it has two 2.
getRandomNumber(5) -> 23153 is not because it has two 3.
Any simple way to do this?
Upvotes: 2
Views: 457
Reputation: 26191
By keeping an array as an hash map, an efficient solution is as follows. However keep in mind that unless it's a string a number can not start with 0.
function getRandomNumber(n){
var a = [],
x = ~~(Math.random()*10),
r = 0;
while (n) {
a[x] === void 0 && (a[x] = true, r += x*Math.pow(10,n-1), --n);
x = ~~(Math.random()*10);
}
return r;
}
console.log(getRandomNumber(3));
console.log(getRandomNumber(4));
console.log(getRandomNumber(5));
console.log(getRandomNumber(6));
console.log(getRandomNumber(7));
Upvotes: 1
Reputation: 842
Don't how to deal with javascript but if it can help you, here a line of scala doing the job
def obtainRestrictedRandomNumber(): Long = scala.util.Random.shuffle((0 to 9)).mkString("").toLong
What it does is simply generating all digits from 0 to 9 then randomize them, concatenate the Array Int elements into a string for finally casting it into a Long.
Upvotes: 0
Reputation: 371049
On each call, make an array of digits, and then repeatedly pick random values and remove them from said array:
function getRandomNumber(n){
const digits = Array.from({ length: 10 }, (_, i) => i);
const result = Array.from({ length: n }, () => {
const randIndex = Math.floor(Math.random() * digits.length);
const digit = digits[randIndex];
digits.splice(randIndex, 1);
return digit;
});
return Number(result.join(''));
}
Array.from({ length: 10 }, () => console.log(getRandomNumber(8)));
Upvotes: 1