Interview Question
Country: United States
public interface ICard extends Comparable {
public static int SPADES = 0;
public static int HEARTS = 1;
public static int CLUBS = 2;
public static int DIAMONDS = 3;
public int getRank();
public int getSuit();
}
public class Card implements ICard {
private final int rank;
private final int suit;
public Card(int rank, int suit) {
this.rank = rank;
this.suit = suit;
}
private String suitDesc[] = {"SPADES", "HEARTS", "CLUBS", "DIAMONDS"};
private String rankDesc[] = {"JOKER", "ACE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN"
, "JACK", "QUEEN", "KING"};
public int getRank() {
return rank;
}
public int getSuit() {
return suit;
}
public int compareTo(Object o) {
ICard other = (ICard)o;
int rankDiff = this.getRank() - other.getRank();
if(rankDiff == 0) {
return this.getSuit() - other.getSuit();
}
return rankDiff;
}
public String toString() {
return rankDesc[rank] + " of " + suitDesc[suit];
}
}
public class Deck implements Iterator<ICard> {
protected ArrayList<ICard> cards;
protected int index = 0;
public Deck() {
cards = new ArrayList<ICard>();
for(int rank = 1; rank <= 13; rank++)
for(int suit = ICard.SPADES; suit <= ICard.DIAMONDS; suit++)
cards.add(new Card(rank, suit));
shuffle();
}
public boolean hasNext() {
return index < cards.size();
}
public ICard next() {
return cards.get(index++);
}
public void remove() {
throw new UnsupportedOperationException();
}
public void shuffle() {
Collections.shuffle(cards);
}
}
It depends what you are you using the pack of cards class for. There are some games which requires the court cards to be separated. Thus I would have had a flag just to denote that it is a court card or if you need the alphabets 'J' , 'Q' etc then it would have been better to have a char denoting it.
Rest all can be kept same.
I would be more interested in the functions you provide from the class.
From the card class: it would have had kept the variables soot, value and cardChar private and initialised through the constructor and then the getter function for each of the variable.
From the class PackOfCards: I would have had a array of the CARD objects and then initailize each of them in the constructor.
how about using flyweight?
- benny August 11, 2012