简体   繁体   中英

Using rand() to generate a number without digit duplicates

How can we customize the code with rand() function in order to generate a n-digit number, where n<8, without digit duplicates in it? Suppose I want to generate a 4 digit number from 1000 to 9999, this number should not contain digit duplicates: for instance 1023 4798, etc. Btw, we may not generalize n.

Edits

I skimmed through the answers in the question I was adressed to. I honestly think that the problem of generating a sequence of digits without a single duplicate in it is in my opinion easier that generating a number with no duplicate digits. Still looking for an answer.

My code is a real mess and truthfully does not contain a single try to tackle the stated problem. I have a paper draft but still it's based on assigning an integer variable to each digit in a number and a small loop which checks if some of them are equal and increment/decrements one of them. This sounds like a bad idea even to me, but this is all I can come to.

You have several obvious choices:

  1. Pick a random number and if it contains any repeating digits, pick again. This can get slow if n is high.

  2. Shuffle the digits from 0 to 9 randomly and take the first n digits.

  3. Keep an array of the remaining digits. Pick an element from the array randomly and remove it from the array. Repeat for the number of digits you need.

If zero is not a legal first digit, you will have to work around that. It should be obvious how to do that in each of these cases. You can always just pick again if the resulting number is too low.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM