Advertisement
Guest User

Untitled

a guest
Jun 24th, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.20 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <errno.h>
  4. #include <limits.h>
  5. #define NUM_CARDS 52
  6. #define SEED 30
  7. static int *shuffle_cards(int *source,unsigned int seed,unsigned int  num_cards)
  8. {
  9.     int *dest = (int *)malloc(num_cards*sizeof(int));
  10.     if(dest==NULL) {
  11.         errno = ENOMEM;
  12.         return NULL;
  13.     }
  14.     srand(seed);
  15.     unsigned int i,to_shuffle,skip_empty;
  16.     for(i=0;i<num_cards;i++) {
  17.         dest[i]=INT_MIN;
  18.     }
  19.     for(to_shuffle=num_cards;to_shuffle!=0;to_shuffle--) {
  20.         skip_empty = (rand()%to_shuffle); //Number of empty blocks that need to be skipped
  21.         i=0;
  22.         while(skip_empty!=0) {
  23.             i++;
  24.             if(dest[i-1]==INT_MIN)
  25.                 skip_empty--;
  26.         }
  27.         //Now skip until we find a free block to put the card
  28.         while(dest[i]!=INT_MIN){
  29.             i++;
  30.         }
  31.         //Now insert the card
  32.         dest[i] = source[(to_shuffle-1)];
  33.     }
  34.     return dest;
  35. }
  36. int main(int argc,char *argv[])
  37. {
  38.     int cards[NUM_CARDS],i;
  39.     int *shuffled;
  40.     for(i=0;i<NUM_CARDS;i++) {
  41.         cards[i] = i+1;
  42.     }
  43.     if( (shuffled = shuffle_cards(cards,SEED,NUM_CARDS)) == NULL ) {
  44.         fprintf(stderr,"Failed to sort cards");
  45.         exit(1);
  46.     }
  47.     printf("Sorted cards are : \n");
  48.     for(i=0;i<NUM_CARDS;i++) {
  49.         printf("%d\n",shuffled[i]);
  50.     }
  51.     free(shuffled);
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement