Basic and Advance C Question:
Download Questions PDF

How can I retHow can I return a sequence of random numbers which dont repeat at all?

Answer:

What you're looking for is often called a ``random permutation'' or ``shuffle.'' One way is to initialize an array with the values to be shuffled, then randomly interchange each of the cells with another one later in the array:
int a[10], i, nvalues = 10;

for(i = 0; i < nvalues; i++)
a[i] = i + 1;

for(i = 0; i < nvalues-1; i++) {
int c = randrange(nvalues-i);
int t = a[i]; a[i] = a[i+c]; a[i+c] = t; /* swap */
}

where randrange(N) is rand() / (RAND_MAX/(N) + 1)

Download C Programming Interview Questions And Answers PDF

Previous QuestionNext Question
How can I generate floating-point random numbers?How can I get random integers in a certain range?