training

Code I wrote during training
git clone git://git.bitsmanent.org/training
Log | Files | Refs | README

fig10_16_mod.c (2008B)


      1 /* Exercise 10.7 */
      2 
      3 /* Fig. 10.16: fig10_16.c
      4    Representing cards with bit fields in a struct */
      5 
      6 #include <stdio.h>
      7 #include <stdlib.h>
      8 
      9 /* bitCard structure definition with bit fields */
     10 struct bitCard {                                  
     11    unsigned face : 4;  /* 4 bits; 0-15 */         
     12    unsigned suit : 2;  /* 2 bits; 0-3 */          
     13    unsigned color : 1; /* 1 bit; 0-1 */           
     14 }; /* end struct bitCard */                       
     15 
     16 typedef struct bitCard Card; /* new type name for struct bitCard */
     17 
     18 void fillDeck( Card * const wDeck );   /* prototype */
     19 void shuffle( Card * const wDeck );    /* prototype */
     20 void deal( const Card * const wDeck ); /* prototype */
     21 
     22 int main(void)
     23 { 
     24    Card deck[ 52 ]; /* create array of Cards */
     25 
     26    fillDeck( deck );
     27    deal( deck );
     28 
     29    return 0; /* indicates successful termination */
     30 
     31 } /* end main */
     32 
     33 /* initialize Cards */
     34 void fillDeck( Card * const wDeck )
     35 { 
     36    int i; /* counter */
     37 
     38    /* loop through wDeck */
     39    for ( i = 0; i <= 51; i++ ) { 
     40       wDeck[ i ].face = i % 13; 
     41       wDeck[ i ].suit = i / 13; 
     42       wDeck[ i ].color = i / 26;
     43    } /* end for */
     44 
     45 } /* end function fillDeck */
     46 
     47 /* shuffle the cards */
     48 void shuffle( Card * const wDeck )
     49 {
     50    int i, j;
     51 
     52    Card temp;
     53 
     54    for(i = 0; i < 52; i++) {
     55       j = rand() % 52;
     56       temp = wDeck[i];
     57       wDeck[i] = wDeck[j];
     58       wDeck[j] = temp;
     59    }
     60 
     61 } /* end function shuffle */
     62 
     63 /* output cards in two column format; cards 0-25 subscripted with 
     64    k1 (column 1); cards 26-51 subscripted k2 (column 2) */
     65 void deal( const Card * const wDeck )
     66 { 
     67    int k1; /* subscripts 0-25 */
     68    int k2; /* subscripts 26-51 */
     69 
     70    /* loop through wDeck */
     71    for ( k1 = 0, k2 = k1 + 26; k1 <= 25; k1++, k2++ ) { 
     72       printf( "Color:%2d  Suit:%2d  Card:%3d   ",
     73          wDeck[ k1 ].color, wDeck[ k1 ].face, wDeck[ k1 ].suit );
     74       printf( "Color:%2d  Suit:%2d  Card:%3d\n",
     75          wDeck[ k2 ].color, wDeck[ k2 ].face, wDeck[ k2 ].suit );
     76    } /* end for */
     77 
     78 } /* end function deal */
     79