2

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?

3 Answers 3

1

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

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

1 Comment

Wow, Amazing solution! It returns a string so please return Number(result.join()).
1

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

1 Comment

~~ a shortcut for Math.floor() for positive real numbers.
0

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.

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.