-
Shuffle Cards and Deal
need to make a program that shuffles a deck of cards and simply deals them into 4 hands
as soon as the program starts it will list something like this:
D9 H5 S10 C4 DJ C10 DA H2 D8 H10 D7 S9 HQ
and 3 more rows of 13
i have got this working correctly but is there anyway i could do it with a double array without using the constant characters. here is my code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
void shuffle( int wdeck[][13]);
void deal( const int wdeck[][13], const char *wface[],
const char *wsuit[]);
void pair( int a[]);
int main()
{
const char *suit[4] = {"H", "D", "C", "S"};
const char *face[13] = {"A", "2", "3", "3", "5",
"6", "7", "8", "9", "10", "J", "Q", "K"};
int deck[4][13] ={0};
srand( time(0));
shuffle(deck);
deal(deck, face, suit);
return 0;
}
void shuffle(int wdeck[][13])
{
int row;
int column;
int card;
for(card = 1; card <= 52; card++) {
do {
row = rand() % 4;
column = rand() % 13;
}while(wdeck [row] [column] !=0);
wdeck [row] [column] = card;
}
}
void deal(const int wdeck[][13], const char *wface[],
const char *wsuit[])
{
int card;
int row;
int column;
for ( card = 1; card <= 52; card++ ) {
for ( row = 0; row <= 3; row++ ){
for ( column = 0; column <=12; column++ ){
if ( wdeck[row][column] == card ) {
printf("%5s%-8s%\n", wface[column], wsuit[row],
card % 52 == 0 );
}
}
}
}_getch();
}
-
Look at std::random_shuffle() in the <algorithm> header.
-
I would say it's better to have an array of one type (int or a special card type) and fill the array with all possible values. Then use random_shuffle on the array and you will have a shuffled deck. You then just iterate through the array to deal the cards. If you use an int, you can use the numbers 0 to 51 (or 1 to 52 or whatever) and use division and modulus to get the suit and rank of each card.
Your code looks like C code, though. If it is, then this should be in the C forum, and you won't be able to use random_shuffle. However, you can still mimic random_shuffle by using a loop. It's easiest to make the loop run from 51 to 0. Get a random number between 0 and the loop index and swap that value with the value at the loop index. Decrement the loop index and continue.