Categories
Programming

Shuffle a deck of cards

The way I found the problem on the web:

Give me an algorithm to shuffle a deck of cards, given that the cards are stored in an array of ints.

2 replies on “Shuffle a deck of cards”

Given a deck of cards encoded as an array pick a pivot point to split the deck in half. Then since shuffled cards are shuffled from the bottom of the split deck we shuffle from the end / back of the deck. The mod
operator makes sure we only swap every other card – otherwise it is just swapping the two halves of the card deck.


void shuffleDeck(card *deck){
  int pivot     = (int)(random() % CARDS_IN_A_DECK);
  int leftIndy  = pivot;
  int rightIndy = CARDS_IN_A_DECK;

  card tmp;
  while(( rightIndy > pivot) && (leftIndy  > 0 )) {

    // Swap the two values.
    if(leftIndy %2){
      tmp = deck[rightIndy];
      deck[rightIndy] = deck[leftIndy];
      deck[leftIndy]  = tmp;
    }

    rightIndy--;
    leftIndy--;
  }
}

Here is my version with the wrapping code.

                                                                                                                                                                                                                   
//------------------------------------------------------------------------------
// Take an array representing a deck of cards and shuffle it.
//------------------------------------------------------------------------------
#include
#include

#define CARDS_IN_A_DECK 52
#define CARDS_IN_A_SUIT 13

typedef enum card_suit_type{ spade, heart, diamond, clover} card_suit;

typedef struct card_struct{
  card_suit suit;
  int value;
} card;

//------------------------------------------------------------
// Shuffle a new deck of cards
//
// Left          Right
// -------      -------
// abcdefg... ...12345
//
// a1b2c3d4e5...
//------------------------------------------------------------


void shuffleDeck(card *deck){
  int pivot     = (int)(random() % CARDS_IN_A_DECK);
  int leftIndy  = pivot;
  int rightIndy = CARDS_IN_A_DECK;

  card tmp;
  while(( rightIndy > pivot) && (leftIndy  > 0 )) {

    // Swap the two values.
    if(leftIndy %2){
      tmp = deck[rightIndy];
      deck[rightIndy] = deck[leftIndy];
      deck[leftIndy]  = tmp;
    }

    rightIndy--;
    leftIndy--;
  }
}


//------------------------------------------------------------
// Create a new deck of cards
//------------------------------------------------------------
card *newDeck()
{
  card *curDecPtr;
  curDecPtr = malloc(sizeof(card) * CARDS_IN_A_DECK);

  int i,j,curIndy;
  for(i= 0; i < 4; i++ ){
    for(j = 0; j

					

Leave a Reply