Amazon Interview Question
Software Engineer / Developerspublic class DeckCards {
public static void main(String[] args) {
int CARDS_PER_PLAYER = 5;
// number of players
int PLAYERS = Integer.parseInt(args[0]);
String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" };
String[] rank = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace" };
// avoid hardwired constants
int SUITS = suit.length;
int RANKS = rank.length;
int CARDS = SUITS * RANKS;
if (CARDS_PER_PLAYER * PLAYERS > CARDS) throw new RuntimeException("Too many players");
// initialize deck
String[] deck = new String[CARDS];
for (int i = 0; i < RANKS; i++) {
for (int j = 0; j < SUITS; j++) {
deck[SUITS*i + j] = rank[i] + " of " + suit[j];
}
}
// shuffle
for (int i = 0; i < CARDS; i++) {
int r = i + (int) (Math.random() * (CARDS-i));
String t = deck[r];
deck[r] = deck[i];
deck[i] = t;
}
// print shuffled deck
for (int i = 0; i < PLAYERS * CARDS_PER_PLAYER; i++) {
System.out.println(deck[i]);
if (i % CARDS_PER_PLAYER == CARDS_PER_PLAYER - 1) System.out.println();
}
}
}
public class Card {
public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX,
SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }
public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
private final Rank rank;
private final Suit suit;
private Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}
public Rank rank() { return rank; }
public Suit suit() { return suit; }
public String toString() { return rank + " of " + suit; }
private static final List<Card> protoDeck = new ArrayList<Card>();
// Initialize prototype deck
static {
for (Suit suit : Suit.values())
for (Rank rank : Rank.values())
protoDeck.add(new Card(rank, suit));
}
public static ArrayList<Card> newDeck() {
return new ArrayList<Card>(protoDeck); // Return copy of prototype deck
}
}
Deck contains list of 52 cards, each card has some info associated with it. Deck has to support Deal and shuffle. set cannot be used because order matters. Shuffle will be a random number function. Deal will be assignment of card to the users.
- Messi April 13, 2010