So, as a task for C, I need to create a card game. Naturally, shuffling be an important part of the code.
I designed the deck to hold cards 52 cards (no jokers), which were identified as integers:
Hundreds would represent the suit, while the tens and ones would represent the face.
I started out by plugging in these numbers into the deck in order first, then shuffled it with a code that basically takes the number from two random indexes in the array and swaps them. This swapping loops for a million times.
However, for some odd reason, after shuffling, the number 0 (Ace of Spades) would always appear twice after shuffling. I wrote a debugging code that would alert when two elements are identical in the array, and it is always 0.
I look through my code over and over, and I can't seem to find the reason why. Is there a characteristic of C that I'm not noticing?
Code:
/* Suit and Face legend:
Suits
000 - Spade
100 - Clover
200 - Diamond
300 - Heart
Faces
0 - Ace
1 - 2
2 - 3
3 - 4
4 - 5
5 - 6
6 - 7
7 - 8
8 - 9
9 - 10
10 - Jack
11 - Queen
12 - King
*/
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#define SUITS 4
#define FACES 13
#define CARDS 52
#define MONEY 500
void debugPrintDeck();
static int deck[CARDS];//deck used in game
int main(){
//Variables
int cnt = -1; //Keeps track of how many cards there are in the deck, as well as the nth card on top. -1 if there's no card in the deck. 0 indexing.
srand(time(0));
puts("Stacking deck in order...");
//PLACING CARDS IN ORDER IN DECK (First Step)
for(int crd = -1; crd < 312;){//Starting from the first Spade (000) to Heart (300)
crd++; //Starts with Ace.
cnt++; //indicating a card has been added to the deck.
deck[cnt] = crd;
if(crd == 12 || crd == 112 || crd == 212 || crd == 312) crd += 87;
}
debugPrintDeck();
puts("\nShuffling in progress...");
//SHUFFLING CODE (Second Step)
//Includes code that will print the values that switch.
//Also include code that will terminate the program when it detects identical numbers in different indexes.
for (int shfl = 1; shfl < 1000000; shfl++){
int rng1 = -1; //initialize to a value not in the deck.
int rng2 = -1;
int temp1 = -1;
int temp2 = -1;
do{
rng1 = rand() % 53;
rng2 = rand() % 53;
} while (rng1 == rng2); //ensures the values won't randomize into the same position.
temp1 = deck[rng1];
temp2 = deck[rng2];
printf("\ntemp1 at deck[%d]= %d",rng1, temp1); //debug
printf(" temp2 at deck[%d]=%d",rng2, temp2); //debug
deck[rng2] = temp1;
deck[rng1] = temp2;
if (deck[rng2] == deck[rng1]) { //debug
printf("\nALERT ALERT ALERT: rng1 #%d is %003d, rng2 #%d is %003d", rng1, deck[rng1], rng2, deck[rng2]);
exit(0);
}
}
debugPrintDeck();
}
void debugPrintDeck(){
puts("\nThe following is the full stack of cards from end to end.");
for (int card = 0; card < 52; card++){
printf("\ncard #%d = %003d", card, deck[card]);
}
}
Note: If you want the program to complete the shuffling and terminate properly, just remove line 82.