0
#include <bits/stdc++.h>

using namespace std;

int main()
{
    srand( time(NULL) );
    int number = (rand() % 9000)+1000;
    cout<<number<<endl;
}

This code helps in generating a 4 digit number but not a distinct one i.e it generates numbers like 4545 , 1561 ,9999 etc.. whereas I want numbers like 1234 ,2395 etc...

1 Answers1

1

You could roll numbers until you get one with distinct digits, but that would be extremely inefficient.

You can either:

  • generate the first digit, and then
  • generate each next digit until it is different from the previous ones
  • put all digits together to form the number

or (more efficient):

  • roll a number between 0-9 for the first digit d1
  • roll a number between 0-8 for the second digit d2 , if d2>=d1 then set d2 += 1
  • roll a number between 0-7 for the third digit, etc...
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • I think the third digit may be same as first if we follow the second approach(efficient) – Tyler Durden Dec 09 '16 at 12:10
  • well the algorithm as written in the answer isnt complete. For the third number you have to `+=1` it if it is `>=d1` and `+=1` if it is `>=d2` and these checks and increments actually have to be done in increasing order of the digits. I didnt want to go to much into detail, but just wrote the general idea. SO isnt a code writing service after all :P – 463035818_is_not_an_ai Dec 09 '16 at 12:12
  • haha yes, fine then ...Thanks – Tyler Durden Dec 09 '16 at 12:14