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.
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.