Amazon Interview Question
Software Engineer / DevelopersSeems like the basic classes would be Deck and Card. I think it's a mistake to use inheritance to designate different types of card; the difference between a two of hearts and a queen of spades is nothing more than data.
For a card, we'd want an int member variable for the value (not zero-based, so it syncs with actual card numbers... one -> ace, five -> five, twelve -> queeen, etc.), and an enum for the suit. It would be trivial to check whether the card was red or black; thus, it's probably not necessary to have a member for that.
The deck class would need some sort of collection of fifty-two cards. Since this is for poker, it's probably safe to assume that we'll only draw from the top of the deck; thus, we can just keep a variable with the number of cards in the deck for use when we shuffle or something so we don't have to worry about the cards we removed, and store it in a simple array. We'd want some sort of "shuffle" method... I'm not familiar with the relative randomness of various algorithms, but what SP suggested sounds fine. We'd of course want a "draw" method that would return the top card of the deck and decrement the card count. The constructor should add all of the possible cards to the deck, but not shuffle, in case the user wants it sorted for some reason.
You would probably want to assign a value of 14 to the ace since in poker, ace is high and not low.
A generic list class with Front Back Split and Shuffle Merge may be. One can also write a shuffle function as
- SP March 20, 2006for i = 1 to n
swap(cards[i], cards[random(i,n)]);