This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I'm in the process of creating a blackjack program and I need for it to deal out cards, but not have them repeat. I was thinking of making each card a variable, but I can't figure out how to make them not repeat themselves.
There are various ways of doing this, but here's one method. It should work regardless of how you choose to represent your cards. Step 1: Throw all of your "cards" into an ArrayList. If you choose to represent your cards as 'int' then you'll have to wrap them (in an Integer). Step 2: Create the holder for the shuffled cards, an ArrayList, or Vector, or array, or however you plan on maintaining the ordered cards. Step 3: Using "Math.random()" select a random card from the first ArrayList, based on how many cards are remaining. So the the first time you'll be generating a number between 0 and 51. Call the "remove(int)" method on the ArrayList to remove the card from the list and return the card. Put that card into the collection you defined in step two. Repeat step 3 until the first list is empty. So the second time you do step #3 you'll generate a number between 0 and 50; the third time a number between 0 and 49, etc. When you finish the first ArrayList will be empty, and the second collection will contain all of the cards in a *random* order.
here's your new favorite method (ya just have to store your Card objects as a list in order to use it): Collections.shuffle(List)
Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood. The hedge "approximately" is used in the foregoing description because default source of randomenss is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm would choose permutations with perfect uniformity. This implementation traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element into the "current position". Elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive. This method runs in linear time. If the specified list does not implement the RandomAccess interface and is large, this implementation dumps the specified list into an array before shuffling it, and dumps the shuffled array back into the list. This avoids the quadratic behavior that would result from shuffling a "sequential access" list in place. Parameters: list - the list to be shuffled. Throws: UnsupportedOperationException - if the specified list or its list-iterator does not support the set method.