how to generate random long int in c where every digit is non-zero? morever the random numbers are reapeting

J.JOE Source

I am making a library management in c for practice. Now, in studentEntry I need to generate a long int studentID in which every number is non-zero.So, I am using this function.

 long int generateStudentID(){
     srand(time(NULL));     
     long int n = 0;
     do
     {
         n = rand() % 10;
     }while(n == 0);
     int i;     
     for(i = 1; i < 10; i++)
     {
         n *= 10; 
         n += rand() % 10;
     }
    if(n < 0)
    n = n * (-1); //StudentID will be positive
    return n;
}

**

  • output
Name : khushit
phone No. : 987546321
active : 1
login : 0
StudentID : 2038393052
Wanted to add another student?(y/n)

** I wanted to remove all zeros from it.Morever when i run the program the first time Random num will be the same as above and second time random num is same as past runs like e.g:-

**program run 1**
StudentID : 2038393052
StudentID : 3436731238
**program run 2**
StudentID : 2038393052
StudentID : 3436731238

Any help will be warmly appreciated. THANKS IN ADVANCE

crandomintlong-integer

Answers

answered 5 days ago gchen #1

Slightly modify the order of your original function should perform the trick. Instead of removing 0s, just do not add 0s.

long int generateStudentID(){
         srand(time(NULL));             
         long int n = 0;         
         for(int i = 0; i < 10; i++)
         {
            long int m = 0;
            do
            {
                m = rand() % 10;
            }while(m == 0);
             n *= 10; 
             n += m;
         }
        //Not needed as n won't be negative
        //if(n < 0)
        //n = n * (-1); //StudentID will be positive
        return n;
    }

answered 5 days ago deamentiaemundi #2

You can either do as gchen suggested and run a small loop that continues until the result is not zero (just like you did for the first digit) or accept a small bias and use rand() % 9 + 1.

The problem with the similar sequences has its reason with the coarse resolution of time(). If you run the second call of the function to fast after the first you get the same seed. You might read this description as proposed by user3386109 in the comments.

comments powered by Disqus