I'm trying to write a short program which deals 20 random playing cards. At the moment I just have a card class, containing a randomCard method, which generates two random numbers and assigns them to a specific suit and value (using switch statements). I then return the card as a string and run a for loop in the main class to print out the 20 cards. I'm struggling to think of a way to check for duplication. How would I virtually take a card out the deck once it is delt so that it isnt generated again?
Hopefully I want to turn this into a full version of the game 'pontoon'. What classes should I use and how should they interact with each other?
Have each card in the deck have a unique identifier (an integer number will do) and store all retrieved identifiers in some data structure (probably an array). Then all you have to do is check whether a new card already exists in that array and generate another one if it does.
Originally posted by Jeroen Wenting: Have each card in the deck have a unique identifier (an integer number will do) and store all retrieved identifiers in some data structure (probably an array). Then all you have to do is check whether a new card already exists in that array and generate another one if it does.
This has one slight disadvantage. Say you are dealing all 52 cards in a standard deck. Once you deal the first 51 cards, theoretically you can infinitely try to generate a new card to deal and always generate one that was already previously dealt. An alternative to this is to create a data structure, either an array or ArrayList would do nicely, that holds all the possible unique cards. Then you pick a random card from the structure and remove it. The next time you deal a card, only the remaining cards in the deck are in the data structure. When you get to the last card, you can easily deal it without having to double-check if your randomly generated card has been dealt already.
Another common technique is to make a collection of the 52 possible card values (maybe just ints 1 through 52) and mix them up (shuffle). Then you can take the first "n" and get a random set. See if you can think of a neat way to mix up a bunch of card numbers.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Along the same lines. You have an array of 52 cards. You randomly pick a number from the size of the array. Take that Card and remove it form the array. Now the array has 51 elements, so the next time you randomly pick a number from the size of the array, it will be from 1 to 51, or actually 0 to 50, subtract one from the randomizer.