Want more features on Pastebin? Sign Up, it's FREE!
Guest

Knuth shuffle - 'Algorithm P' C code

By: a guest on Feb 4th, 2012  |  syntax: C  |  size: 1.17 KB  |  views: 77  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. int main(int argc, char *argv[])
  6. {
  7.     // Define the size of the array and initialize it.
  8.     #define ARRAY_SIZE 10
  9.     int array[ARRAY_SIZE];
  10.      
  11.     // For this example the array to be shuffled is filled with the values 0..9.
  12.     int i;
  13.     for (i = 0; i < ARRAY_SIZE; i++)
  14.         array[i] = i;
  15.      
  16.     // Initialize the random number generator.
  17.     srand((unsigned) time(NULL));
  18.      
  19.     // Start at the length of the array.
  20.     int index = ARRAY_SIZE;
  21.      
  22.     // Note the use of "index > 1" rather than "index > 0". If "index > 0" was used
  23.     // then the final pass through the loop would always swap index 0 with itself.
  24.     while (index > 1)
  25.     {
  26.         // Create a random number in the range 0..index-1.
  27.         int randomNum = (int) ((double) rand() / ((double) RAND_MAX + 1) * index);
  28.  
  29.         // Decrement index by 1, the loop travels down through the array.
  30.         index = index - 1;
  31.  
  32.         // Swap the array elements at positions index and randomNum.
  33.         int temp = array[index];
  34.         array[index] = array[randomNum];
  35.         array[randomNum] = temp;
  36.     }
  37.     return 0;
  38. }
clone this paste RAW Paste Data