Advertisement
cd62131

Shuffle

Dec 6th, 2013
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.94 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #define N 10
  5.  
  6. unsigned char **make(int n) {
  7.   unsigned char **p = (unsigned char **) malloc(N * sizeof(unsigned char *));
  8.   for (int i = 0; i < n; i++) {
  9.     p[i] = (unsigned char *) malloc(BUFSIZ);
  10.     sprintf((char *) p[i], "Q%d.", i);
  11.   }
  12.   return p;
  13. }
  14.  
  15. void print_problem(unsigned char **problem, int n) {
  16.   for (int i = 0; i < N; i++) {
  17.     printf("%s ", problem[i]);
  18.   }
  19.   printf("\n");
  20. }
  21.  
  22. void shuffle(unsigned char **problem, int n) {
  23.   srand((unsigned int) time(NULL));
  24.   for (int i = n - 1; i > 0; i--) {
  25.     int j = rand() % (i + 1);
  26.     unsigned char *swap = problem[i];
  27.     problem[i] = problem[j];
  28.     problem[j] = swap;
  29.   }
  30. }
  31.  
  32. int main(int argc, char **argv) {
  33.   unsigned char **problem = make(N);
  34.   printf("Before:\n");
  35.   print_problem(problem, N);
  36.   shuffle(problem, N);
  37.   printf("After:\n");
  38.   print_problem(problem, N);
  39.   return EXIT_SUCCESS;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement