C Interview Questions and Answers


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

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)

Posted by:Richards