Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

card shuffling algorithmn 1

Status
Not open for further replies.

blues77

Programmer
Jun 11, 2002
230
CA
Hello,

I'm trying to figure out a way to simulate the shuffling a deck of cards. At the moment I have a vector that holds all 52 cards in the deck. I was thinking of having a for loop and for each iteration generating a random number and then taking the card in the vector being pointed to by the iterator and adding it to a new vector in the position generated by the random number. This should work however, it isn't really efficient since often times the space in the shuffled deck (determined by the random number) will be occupied and the algorithmn will have to try again and generate a new random number until it finds a position in the vector that is unoccupied. If anyone has any ideas on a better algorithmn I would appreciate hearing from you.

Thanks
 
That's pretty funny, I am doing almost the same thing. I settled on this (with cardList being an ArrayList, but it should work with a Vector, too):
Code:
Collections.shuffle(cardList, new Random());
The algorithm used is a common shuffling algorithm where you start your loop at the back, then randomly choose an element in the vector before the current one to swap with it.

So if you didn't want to use the built-in shuffle method, you could do the same thing with a for loop.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top