简体   繁体   中英

How do you shuffle a non-standard deck of cards?

I am making a program to play a game of UNO. In the UNO deck, some cards are repeated, and therefore I cannot just make a list of integers; I have to use objects. I plan on using a LinkedList for the deck, but I am aware that shuffles on a LinkedList are horridly slow.

My question is, should I....

  1. Avoid a LinkedList entirely and just go with an ArrayList
  2. Use an ArrayList or similar, shuffle, then put the contents into the LinkedList
  3. Construct an ArrayList, then make my own shuffling routine (aka not using Random) that adds to the LinkedList as we go
  4. Shuffle the LinkedList anyway (as in, it's not really that bad)

This is not for homework; it is to assist in having fun :)

You can represent cards by plain integers. If an integer represents a type of card, and Uno has multiple cards of the same type, just use the integer corresponding to that card more than once.

Shuffling and dealing is easy.

To start the game, set up a fixed size, dumb array of type integer (no fancy linked lists or Arraylist need apply) that can hold the entire deck (size = N). Fill this array with the integers representing the Uno deck including the duplicate integers representing duplicate cards. Set UNDEALT to N.

To shuffle, execute the following code some modest (100?) times:

 1)  Pick a random number from 1 to UNDEALT, R.
 2)  Exchange the the first array slot with the Rth slot.

To deal:

 1) Give out the card in the UNDEALT slot.
 2) Decrement UNDEALT.

You can do all this with fancier data structures, too, but there just isn't any point. Given that the total information involved is 100 data items, unless you do something outrageously dumb, it'll be faster than people. But my motto is: if simple works, stick with simple.

A few thoughts:

cards[] = {1, 1, 1, 1, 2, 3, 4, 5, 6, 6} , where 1 = "Wild", 2 = "Draw Four", or what have you.

In my opinion, using an Array(List) would make it easiest to do so. The difference here is using the array's values for gameplay, rather than their keys to determine what the card is.

You can do the same thing with objects if you'd like; you shuffle the array based on array index, but use the values in the array (objects representing cards) to know what the card actually is.

edit: Apparently Java will shuffle things for you! http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List)

If you don't shuffle too often, it won't be that slow.

One way to shuffle is to randomly permute the first card with another one. This isn't that slow with a LinkedList. Copying it to/from an ArrayList, on the other hand, is going to take some time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM