/* Generating a pseudo-random permutation of N integers. See p. 139 of "Seminumerical Algorithms, 2nd edition," by Donald Knuth, for more details. Thanks to Jason Bergner for sending me code implementing Knuth's algorithm. */ #include #include main() { int i, k, N = 10, a[100], temp; /* Initialize the random number generator, using the current time as a seed */ srandom( (int)time(NULL) ); /* Initialize the array to contain 0,1,2,...,N-1 */ for( i=0; i < N; i++ ) a[i] = i; /* Do a bunch of random swaps--try it by hand to see what's happening. */ for( i=N-1; i > 0; i-- ) { k = (int)(random() % (i+1)); temp = a[k]; a[k] = a[i]; a[i] = temp; } /* Here's the resulting permutation. */ for( i=0; i < N; i++ ) printf( "%d ", a[i] ); putchar( '\n' ); }