1

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.

Community
  • 1
  • 1
Z. Diyas
  • 13
  • 4
  • 1
    I'm not sure that duplicate is appropriate. This is asking how to keep the digits from repeating, not the numbers in the sequence. I think you could do this by shuffling the digits 0-9 and taking the first 'n' digits. – Fred Larson Feb 04 '16 at 19:05
  • 1
    I agree it is not the same question, but what have you tried? Please post your code, and show where it is failing. – Weather Vane Feb 04 '16 at 19:10
  • I'm not working specifically on this problem, I'm kind of new in programming and just started to learn. I really tried my best to surf the internet from the bottom to the top, but still couldn't find the fitting answer. – Z. Diyas Feb 04 '16 at 19:28

1 Answers1

3

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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278