View Single Post
Old Feb 3rd, 2005, 12:43 PM   #7
Eggbert
Professional Programmer
 
Eggbert's Avatar
 
Join Date: Nov 2004
Posts: 250
Rep Power: 5 Eggbert is on a distinguished road
There are several options when it comes to what you want. The most obvious is also the least efficient. That option is randomly shuffling the array by copying the strings with strcpy and the like. A better option is to maintain an array of pointers to the strings that you can easily shuffle, or an array of indices.

Here is an implementation for the option using an array of indices:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define N_NAMES 15
#define MAX_LEN 10

int main ( void )
{
  char names[N_NAMES][MAX_LEN];
  int index[N_NAMES];
  int i, j;

  for ( i = 0; i < N_NAMES; i++ ) {
    printf ( "Enter name #%d: ", i + 1 );
    fflush ( stdout );

    if ( fgets ( names[i], MAX_LEN, stdin ) == NULL )
      break;

    index[i] = i;
  }

  srand ( (unsigned)time ( NULL ) );

  /* Random shuffle */
  for ( j = 0; j < i; j++ ) {
    int r = rand() % ( i - j ) + j;
    int save = index[j];
    index[j] = index[r];
    index[r] = save;
  }

  for ( j = 0; j < i; j++ )
    printf ( "%s", names[index[j]] );

  getchar();

  return 0;
}
Eggbert is offline   Reply With Quote