|
|
1.1 root 1: static char *sccsid = "@(#)cards.c 1.4 (Berkeley) 5/19/83";
2:
3: #include <stdio.h>
4: #include "deck.h"
5:
6:
7: /*
8: * initialize a deck of cards to contain one of each type
9: */
10:
11: makedeck( d )
12:
13: CARD d[];
14: {
15: register int i, j, k;
16: long time();
17:
18: i = time( (long *) 0 );
19: i = ( (i&0xff) << 8 ) | ( (i >> 8)&0xff ) | 1;
20: srand( i );
21: k = 0;
22: for( i = 0; i < RANKS; i++ ) {
23: for( j = 0; j < SUITS; j++ ) {
24: d[k].suit = j;
25: d[k++].rank = i;
26: }
27: }
28: }
29:
30:
31:
32: /*
33: * given a deck of cards, shuffle it -- i.e. randomize it
34: * see Knuth, vol. 2, page 125
35: */
36:
37: shuffle( d )
38:
39: CARD d[];
40: {
41: register int j, k;
42: CARD c;
43:
44: for( j = CARDS; j > 0; --j ) {
45: k = ( rand() >> 4 ) % j; /* random 0 <= k < j */
46: c = d[j - 1]; /* exchange (j - 1) and k */
47: d[j - 1] = d[k];
48: d[k] = c;
49: }
50: }
51:
52:
53:
54: /*
55: * return true if the two cards are equal...
56: */
57:
58: eq( a, b )
59:
60: CARD a, b;
61: {
62: return( ( a.rank == b.rank ) && ( a.suit == b.suit ) );
63: }
64:
65:
66:
67: /*
68: * isone returns TRUE if a is in the set of cards b
69: */
70:
71: isone( a, b, n )
72:
73: CARD a, b[];
74: int n;
75: {
76: register int i;
77:
78: for( i = 0; i < n; i++ ) {
79: if( eq( a, b[i] ) ) return( TRUE );
80: }
81: return( FALSE );
82: }
83:
84:
85:
86: /*
87: * remove the card a from the deck d of n cards
88: */
89:
90: remove( a, d, n )
91:
92: CARD a, d[];
93: int n;
94: {
95: register int i, j;
96:
97: j = 0;
98: for( i = 0; i < n; i++ ) {
99: if( !eq( a, d[i] ) ) d[j++] = d[i];
100: }
101: if( j < n ) d[j].suit = d[j].rank = EMPTY;
102: }
103:
104:
105:
106: /*
107: * sorthand:
108: * Sort a hand of n cards
109: */
110: sorthand(h, n)
111: register CARD h[];
112: int n;
113: {
114: register CARD *cp, *endp;
115: CARD c;
116:
117: for (endp = &h[n]; h < endp - 1; h++)
118: for (cp = h + 1; cp < endp; cp++)
119: if ((cp->rank < h->rank) ||
120: (cp->rank == h->rank && cp->suit < h->suit)) {
121: c = *h;
122: *h = *cp;
123: *cp = c;
124: }
125: }
126:
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.