the cards have to alternate like top half and bottom half in this order till it goes through a 52 card deck. Each deck half has 26 cards they go in the following order:
top1, bottom1, top2, bottom2, top3, bottom3, top4, bottom 4, ..., top n, bottom n
I was thinking of doing this: Card[] topHalf= new Card[cards.length/2];
public void shuffle() {
int index = 0;
for (int suit = 0; suit <= 1; suit++) {
for (int value = 1; value <= 13; value++) {
cards[index] = new Card(value, suit);
index++;
}
}
Card[] botHalf= new Card[(cards.length+26)/2];
int index2 = 0;
for (int suit = 2; suit <= 3; suit++) {
for (int value = 1; value <= 13; value++) {
cards[index] = new Card(value, suit);
index2++;
开发者_如何学C
}
for (int row = 0; row < cards.length; row++){
row++;
Card [] temp = new Card[( topHalf.length)+botHalf.length];
//cards[row]= cards[index];
}
Store the cards in a Sorted Map using the order in which they are to appear as a key. The Sorted Map will do the sorting for you. You can then iterate through them all in order:
SortedMap map = new SortedMap();
map.put(1, "top1");
map.put(2, "bottom1");
map.put(3, "top2");
...
...
...
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
Object key = iterator.next();
System.out.println(" card :" + map.get(key));
}
Just to clarify, it sounds like the shuffle you want would arrange the numbers
1 2 3 4 5 6 7 8
as
1 8 2 7 3 6 4 5
.
The most efficient way to do this is to create a new array, since swapping elements around in-place isn't easy and won't be fast. The key observation in this pattern is that every even element (starting with index 0, so the first element is even) counts upwards from the start of the deck, and odd element counts backwards from the end of the deck.
Using this information, we can loop over the new array, copying in the values from a specific index the original array, based upon whether the current index is odd or even. If the current index in our new array is called i
, then
- If
i
is even, then the element we want is at indexi/2
- If
i
is odd, then the element is at indexarray.length - (i+1)/2
(the+1
is to round up to the nearest even number)
Here is the code:
public static Card[] rifleShuffle(Card[] deck) {
Card[] newDeck = new Card[deck.length];
for (int i = 0; i < newDeck.length; i++) {
// Check whether current index is odd or even by using mod 2
if (i % 2 == 0) {
newDeck[i] = deck[i / 2];
} else {
newDeck[i] = deck[deck.length - ((i + 1) / 2)];
}
}
return newDeck;
}
public static void main(String[] args) {
Card[] deck1 = new Card[52];
int i = 0;
for (int suite = 0; suite < 4; suite++) {
for (int value = 1; value <= 13; value++) {
deck1[i++] = new Card(value, suite);
}
}
System.out.println("Before shuffling: " + Arrays.toString(deck1));
Card[] deck2 = rifleShuffle(deck1);
System.out.println("After shuffling: " + Arrays.toString(deck2));
}
精彩评论