I am trying to write a card shuffler, and I know the method by which I wish to shuffle the cards. However, I am at a loss of the best object-oriented way in which to write it.
The method, a rather common one, is as follows:
- Assign each a random numeric value, between 0 and 2,147,483,647
- If there is a duplicate key value (very unlikely), throw away the deck, and start again.
- Store the cards in a set
- Order the set by each cards key value
My problem lies in the best OOP way to write this. At first I came up with an object called Card, containing a suit value, a number value and the random key value. Then I would have a class called Deck that extended a HashSet, and I would store each card into the HashSet and then sort it by key value. Where I struggled was, what is the most efficient way to ‘generate’ the 52 Card objects in the first place, and how to order the set. Would I implement the interface, ‘SortedSet’, if so, how would I go about writing the comparators?
Quite a broad question, more based on OOP design practices, but I’d like this to be a really smooth and object based solution.
Cheers,
Tim.
EDIT:
Thanks for the help everyone. My solution was as follows:
- 2 Enums (CardValues, CardSuits), containing the 4 suits and 13 possible values
- Card class, that takes as constructor arguments a CardValue and a CardSuit.
- Deck class that extends a TreeMap
When a new deck is created and shuffled, I loop through the CardSuit Enum and created Cards, then inside that loop, I go through the CardValue Enum. This creates the cards, I then generate a random key and put them in the TreeMap.
As there is always a small chance of key repetition, if the final deck size is not 52, I throw a new InvalidDeckException.
Thanks for the suggestions, I am much happier with this solution.
Use a
TreeMap, for each card generate a random number that doesn’t exist in the map, and insert it in the map as the key for the card, done.The map is now ordered by the random numbers generated.
See also http://en.wikipedia.org/wiki/Shuffling#Shuffling_algorithms
Note that this is a retarded way to shuffle, just use
Collections.shuffle().