I am trying to develop a program that shuffles a deck by dividing the deck into two and then interlacing them.
Class Deck represents a deck of 52 cards. There a
Ok, dear, actually you get a "index out of bounds" (god knows why... :), here is how i solved it (with comments):
public class Deck {
//constants for 52 and 26 :
private static final int FULL_DECK = Suit.values().length * Rank.values().length;
private static final int HALF_DECK = FULL_DECK / 2;
// use the constants, we need only one list (+2 temp lists, throw away
// "shuffeld" (not needed, confusing, we use "cards" for "full deck")):
private final ArrayList<Card> cards = new ArrayList<>(FULL_DECK);
public Deck(int n) {
init(); // as you had/see below
// more overview/structure ... and we can limit n:
for (int rounds = 0; rounds < n % 8; rounds++) {
interlace();
}
// comment this, since we do output in main method...
// System.out.println(cards);
}
init & "interlace" methods:
private void init() {
for (Suit s : Suit.values()) {
for (Rank r : Rank.values()) {
cards.add(new Card(r, s));
}
}
}
private void interlace() {
// throw exception, when illegal state
assert (!cards.isEmpty());
// left & right temp lists:
final ArrayList<Card> left = new ArrayList<>(HALF_DECK);
final ArrayList<Card> right = new ArrayList<>(HALF_DECK);
// put the first half of "cards" into "left"
left.addAll(cards.subList(0, HALF_DECK));
// ...the rest into "right"
right.addAll(cards.subList(HALF_DECK, FULL_DECK));
// clear "cards"
cards.clear();
// iterate half deck:
for (int i = 0; i < HALF_DECK; i++) {
// fill cards from "left" (with "double step")
cards.add(i * 2, left.get(i));
// ..and from "right" (with "double step" +1;)
cards.add(i * 2 + 1, right.get(i));
}
// done!
// debug:
// System.out.println(left);
// System.out.println(right);
// System.out.println(cards);
}
the "draw" method would go like this:
public Card drawCard() {
assert (!cards.isEmpty());
return cards.remove(0);
}
And with the same main method (Suit, Rank classes), we get:
The original deck is:
S2 S3 S4 S5 S6 S7 S8 S9 S10 SJ SQ SK SA H2 H3 H4 H5 H6 H7 H8 H9 H10 HJ HQ HK HA C2 C3 C4 C5 C6 C7 C8 C9 C10 CJ CQ CK CA D2 D3 D4 D5 D6 D7 D8 D9 D10 DJ DQ DK DA
After shuffling once is:
S2 C2 S3 C3 S4 C4 S5 C5 S6 C6 S7 C7 S8 C8 S9 C9 S10 C10 SJ CJ SQ CQ SK CK SA CA H2 D2 H3 D3 H4 D4 H5 D5 H6 D6 H7 D7 H8 D8 H9 D9 H10 D10 HJ DJ HQ DQ HK DK HA DA
After shuffling twice is:
S2 H2 C2 D2 S3 H3 C3 D3 S4 H4 C4 D4 S5 H5 C5 D5 S6 H6 C6 D6 S7 H7 C7 D7 S8 H8 C8 D8 S9 H9 C9 D9 S10 H10 C10 D10 SJ HJ CJ DJ SQ HQ CQ DQ SK HK CK DK SA HA CA DA
It's not "that" thread safe ...but for demo purpose... hope it helps! :)
..and the index out of bounds actually, because you never filled shuffeled
, when n == 0
... iobex at Main: System.out.print(deck.drawCard() + " ");
(and (n == 0
))