forked from AllenDowney/ThinkJavaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCard.java
More file actions
131 lines (108 loc) · 2.83 KB
/
Copy pathCard.java
File metadata and controls
131 lines (108 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/**
* A standard playing card.
*/
public class Card {
public static final String[] RANKS = {
null, "Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"};
public static final String[] SUITS = {
"Clubs", "Diamonds", "Hearts", "Spades"};
private final int rank;
private final int suit;
/**
* Constructs a card of the given rank and suit.
*/
public Card(int rank, int suit) {
this.rank = rank;
this.suit = suit;
}
/**
* Returns a negative integer if this card comes before
* the given card, zero if the two cards are equal, or
* a positive integer if this card comes after the card.
*/
public int compareTo(Card that) {
if (this.suit < that.suit) {
return -1;
}
if (this.suit > that.suit) {
return 1;
}
if (this.rank < that.rank) {
if (this.rank == 0 && that.rank == 13) {
return 1;
}
else{
return -1;
}
}
if (this.rank > that.rank) {
if (this.rank == 13 && that.rank == 0) {
return -1;
}
else {
return 1;
}
}
return 0;
}
/**
* Returns true if the given card has the same
* rank AND same suit; otherwise returns false.
*/
public boolean equals(Card that) {
return this.rank == that.rank
&& this.suit == that.suit;
}
/**
* Gets the card's rank.
*/
public int getRank() {
return this.rank;
}
/**
* Gets the card's suit.
*/
public int getSuit() {
return this.suit;
}
/**
* Returns the card's index in a sorted deck of 52 cards.
*/
public int position() {
return this.suit * 13 + this.rank - 1;
}
/**
* Returns a string representation of the card.
*/
public String toString() {
return RANKS[this.rank] + " of " + SUITS[this.suit];
}
public Card[] makeDeck() {
Card[] deck = new Card[52];
int index = 0;
for (int suit = 0; suit < SUITS.length; suit++) {
for (int rank = 1; rank < RANKS.length; rank++) {
deck[index] = new Card(rank, suit);
index++;
}
}
return deck;
}
public int[] suitHist(Card[] hand) {
int[] hist = new int[4];
for (int i = 0; i < hand.length; i++) {
hist[hand[i].suit]++;
}
return hist;
}
public boolean hasFlush(Card[] hand) {
int[] hist = suitHist(hand);
for (int i = 0; i < hist.length; i++) {
if (hist[i] >= 5) {
return true;
}
}
return false;
}
}