Card Shuffling

From Public Wiki
Revision as of 01:44, 22 December 2020 by Legg (talk | contribs) (Created page with "==Synopsis== Define a deck of cards in an array. Shuffle these cards in O(n) time using modulus arithmetic ==Notes== This code is specifically designed to leave an occasio...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Synopsis

Define a deck of cards in an array. Shuffle these cards in O(n) time using modulus arithmetic

Notes

This code is specifically designed to leave an occasional card in it's original location.

Code

  1. include<stdio.h>
  2. include<stdlib.h>
  3. include<time.h>
  1. define NUM_CARDS 52

int main(void) { short counter_a; short d; time_t t; char a[NUM_CARDS]; char c;

const char *n[NUM_CARDS];


n[0] = "Ace of spades"; n[1] = "2 of spades"; n[2] = "3 of spades"; n[3] = "4 of spades"; n[4] = "5 of spades"; n[5] = "6 of spades"; n[6] = "7 of spades"; n[7] = "8 of spades"; n[8] = "9 of spades"; n[9] = "10 of spades"; n[10] = "Jack of spades"; n[11] = "Queen of spades"; n[12] = "King of spades"; n[13] = "Ace of hearts"; n[14] = "2 of hearts"; n[15] = "3 of hearts"; n[16] = "4 of hearts"; n[17] = "5 of hearts"; n[18] = "6 of hearts"; n[19] = "7 of hearts"; n[20] = "8 of hearts"; n[21] = "9 of hearts"; n[22] = "10 of hearts"; n[23] = "Jack of hearts"; n[24] = "Queen of hearts"; n[25] = "King of hearts"; n[26] = "Ace of clubs"; n[27] = "2 of clubs"; n[28] = "3 of clubs"; n[29] = "4 of clubs"; n[30] = "5 of clubs"; n[31] = "6 of clubs"; n[32] = "7 of clubs"; n[33] = "8 of clubs"; n[34] = "9 of clubs"; n[35] = "10 of clubs"; n[36] = "Jack of clubs"; n[37] = "Queen of clubs"; n[38] = "King of clubs"; n[39] = "Ace of diamonds"; n[40] = "2 of diamonds"; n[41] = "3 of diamonds"; n[42] = "4 of diamonds"; n[43] = "5 of diamonds"; n[44] = "6 of diamonds"; n[45] = "7 of diamonds"; n[46] = "8 of diamonds"; n[47] = "9 of diamonds"; n[48] = "10 of diamonds"; n[49] = "Jack of diamonds"; n[50] = "Queen of diamonds"; n[51] = "King of diamonds";

//Spice up the random function. srand((unsigned) time(&t));

//initialize with unsorted numbers for(counter_a=0;counter_a<NUM_CARDS;counter_a++) { a[counter_a] = counter_a; }

counter_a--; while(counter_a>0) { //if statement, because sometimes we don't want to //always swap a card. The larger the comparison //number, the more frequently it is that a pair //isn't swapped

if(rand() % (NUM_CARDS)>2) { d=rand() % counter_a; c=a[counter_a]; a[counter_a]=a[d]; a[d]=c; } counter_a--; }

printf ("Unsorted\n");

for(;counter_a<NUM_CARDS;counter_a++)

       {
               printf(" %s\n", n[a[counter_a]]);
       }

printf("Done !\n"); return 0; }


</syntaxhighlight>