0

Code

Random Randomizer = new Random () ;
  cardoneA = suits[Randomizer.nextInt(suits.length)];
  cardoneAv = ranks[Randomizer.nextInt(ranks.length)];

How can I stop the Randomizer from picking the same cards twice? Eg. If it picks a certain suit and rank, how can I stop it from picking it again? Also, how can I make it pick those two together, so that it can pick another card of the same value, as long as its a different class?

2
  • One method is to keep track of whether you have chosen a card and loop until you choose an unchosen card. Commented Sep 19, 2012 at 1:30
  • How do you expect a Randomizer to choose values that you expect it to be? It can only randomize and it's only a coincidence that it chose a value more than once. However, to reduce this coincidence, you will have to increase the range of integers nextInt() looks into. Commented Sep 19, 2012 at 1:30

4 Answers 4

5

Just simulate a deck of cards like you would do it in real-life:

  1. Store all cards which were not drawn yet in an ArrayList.
  2. generate a random number between 0 and the current size of the ArrayList
  3. remove the card which was picked. The array is now one less in size.

This algorithm is also known as the Fisher-Yates Shuffle.

Sign up to request clarification or add additional context in comments.

Comments

2

Rather than keeping track of the card that you have picked, keep track of the card that you haven't picked, and randomize the number to choose among those that you haven't picked.

  1. Initialize a list with all possible combination
  2. Generate a random number within 0 to (number of unchosen cards - 1)
  3. Pick the card and remove the card from the list
  4. Repeat step 2 and 3 until you have necessary number of cards, or all the cards have been chosen.

Comments

2

You can't prevent the randomizer from returning the same index multiple times. You'll need to keep a list of which cards - a combination of suit index and rank index - have already been chosen, and pick new random indices in a loop, looping until you get a card that you haven't already picked.

1 Comment

The problem with that algorithm is that it will become quite slow when most of the cards are picked. When you have a very large deck of cards, it could take hundreds of randomly generated numbers to choose between the last few cards.
1

Are you trying to shuffle them?

If so, the single line statement list.add(list.remove(n)); where n is a random number from 0 to list.size() - 1. Repeat this around 500 times for decent shuffling. What this does is a common shuffle; take out a random card, put it on the top.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.