Skip to content

Instantly share code, notes, and snippets.

@SoftwareJock
Created November 9, 2014 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SoftwareJock/02f3fe870de51accf5df to your computer and use it in GitHub Desktop.
Save SoftwareJock/02f3fe870de51accf5df to your computer and use it in GitHub Desktop.
Java code for Deck of Cards
/**
*
* Deck of Cards Problem.
*
* November 7, 2014
*
* @author Edward J. Joyce
*/
import java.util.Random;
public class PlayingCards {
private byte[] cardDeck = new byte[52];
private byte toBeDealt = 0;
public PlayingCards() {
// Initialize the card deck.
for (byte index = 0; index < 52; index++) {
cardDeck[index] = index;
}
} // constructor
// Uses the Fisher-Yates shuffle algorithm.
public void shuffle() {
Random randomNumbers = new Random();
for (byte index = (byte) (cardDeck.length - 1); index > 0; index--) {
int randomPlace = randomNumbers.nextInt(index + 1);
// Exchange.
byte swapCard = cardDeck[randomPlace];
cardDeck[randomPlace] = cardDeck[index];
cardDeck[index] = swapCard;
}
} // shuffle
// This logic assumes that shuffle will not be called following calls to dealOneCard.
// Returns:
// 0 - 51, dealt card
// if dealt%13 = 0, card is an ace
// = 1 - 9, card is a numbered card 2 - 10
// = 10, card is a jack
// = 11, card is a queen
// = 12, card is a king
//
// if dealt/13 = 0, card is a heart
// = 1, card is a spade
// = 2, card is a club
// = 3, card is a diamond
//
// -1, deck is empty (all cards have already been dealt)
public byte dealOneCard() {
if (toBeDealt >= cardDeck.length) {
return -1;
}
return cardDeck[toBeDealt++];
} // dealOneCard
} // PlayingCards
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment