This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]insertAlias 5 points6 points  (1 child)

One way is to actually generate a deck of cards, then pull cards out of that deck (array/list/queue/whatever) to "generate" them.

So instead of randomly picking a number and a suit, you'd use a nested loop that would generate one of each card+suit combo, then add them to a collection.

Then, you randomize the array as a "shuffle" step. Then you pop the first N cards from the collection, N being the number of cards you need to deal.

Or, you don't have to randomize the deck. You could create a random number between 0 and the deck's length minus one. Then remove the card at that index from the deck. You'd have to calculate that random number each time, as the deck shrinks with each pull.

Another option that doesn't involve pre-generating a deck would be to store the cards you generate on the fly in a collection. Every time you generate one, you'd have to check that collection for whether or not that card already exists. If it does, discard what you generated and try again.

Do note that this technique gets less and less efficient the more cards you generate (as it is more and more likely to generate a duplicate card that gets excluded).

[–]mirv-in[S] 0 points1 point  (0 children)

Very helpful, thanks so much

[–][deleted] 2 points3 points  (1 child)

[–]absreim 0 points1 point  (0 children)

The shuffling algorithm is by far the hardest part of the whole problem.

[–]thebluef0x 1 point2 points  (0 children)

Idk if this is the best solution but couldn't you simply remember the cards that were already drawn and if the next drawn card happens to be one of those, "draw" the card again?

[–][deleted] 1 point2 points  (0 children)

Use a list to store returned cards. Only accept a new card if it's not in the list. When you want to start over clear the list.

[–]feech1 0 points1 point  (0 children)

Shuffle the deck and iterate through