This is a design round. You write the classes, and the interviewer checks that they behave.
Here you build a deck of playing cards. You can cut it, shuffle it and deal from it.
A card has a rank and a suit. The ranks in order are A 2 3 4 5 6 7 8 9 10 J Q K. The suits in order are C D H S (clubs, diamonds, hearts and spades).
Implement two classes:
NewCard(rank, suit)makes a card.- The card's
label()returns its rank and then its suit, such as"10H". NewDeck()makes a new deck of 52 cards.cut(k)moves the topkcards to the bottom. They keep their order.perfectShuffle()splits the deck into a top half and a bottom half. Then it takes one card from each half in turn, starting with the top half.deal(count)takescountcards off the top and returns them, top card first. If fewer cards are left, it returns all of them.remaining()returns how many cards are left.
Go has no classes. Card and Deck are structs, made by NewCard and NewDeck. The deck's methods have a pointer receiver, *Deck, because they change it.
A new deck holds the clubs from A to K, then the diamonds, hearts and spades. So AC is on top and KS is at the bottom.
When the number of cards is odd, the top half gets the extra card. For example, the five cards 1 2 3 4 5 shuffle into 1 4 2 5 3. Nothing here is random.
The calls run in order on one new deck. The output has one line for each deal and remaining call. A deal line lists the labels with a space between them. It says none when no card was dealt.
Example 1:
Input: NewDeck() 1. deal(3) 2. remaining() 3. cut(10) 4. deal(2) 5. remaining() Output: AC 2C 3C 49 AD 2D 47 Explanation: Call 1 deals the top three clubs. Call 3 moves the other ten clubs to the bottom. So the diamonds are on top for call 4.
Example 2:
Input: NewDeck() 1. perfectShuffle() 2. deal(4) 3. remaining() Output: AC AH 2C 2H 48 Explanation: The top half holds the clubs and the diamonds. The bottom half holds the hearts and the spades. So the shuffled deck starts with AC, AH, 2C and 2H.
Example 3:
Input: NewDeck() 1. perfectShuffle() 2. perfectShuffle() 3. perfectShuffle() 4. perfectShuffle() 5. perfectShuffle() 6. perfectShuffle() 7. perfectShuffle() 8. perfectShuffle() 9. deal(5) Output: AC 2C 3C 4C 5C Explanation: Eight perfect shuffles bring a full deck back to its first order.
Constraints:
kis a whole number from 0 to the number of cards left.countis a whole number from 1 to 1,000,000,000.- At most 1,000 calls are made on one deck.
Note:
Each call should take at most O(n) time, where n is the number of cards in the deck. That holds for deal too, even when it asks for more cards than are left.
Free plan: 30 tutor messages. Premium is unlimited.
