473,806 Members | 2,790 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C ++ Shuffling a deck of 52 cards, and handing 5 cards to 2 players

1 New Member
I'm trying to shuffle a deck of card in C ++, with out having the same card twice. And I'm supposed to give each player 5 cards. And if they want, they can replace 3 cards. Right now I can assign 5 cards to each player, but some of the cards repeat themselces (ex. I have 3 Ace of spades, or 2 king of clubs, etc). Can anyone help me fix this problem. Here is what I have so far.

Expand|Select|Wrap|Line Numbers
  1. #include <iostream> 
  2. #include <ctime> 
  3. #include <cstdlib>
  4. #include <cmath>
  5.  
  6.  
  7. using namespace std;
  8. using std::cout;
  9. using std::strncpy;
  10.  
  11. //int random;
  12.  
  13. int main() 
  14.    srand((unsigned)time(0));
  15.  
  16.     string  heart[] =  {"A\3","2\3","3\3","4\3","5\3","6\3","7\3","8\3","9\3","10\3","J\3","Q\3","K\3"};
  17.     string diamond[] = {"A\4","2\4","3\4","4\4","5\4","6\4","7\4","8\4","9\4","10\4","J\4","Q\4","K\4"};
  18.     string  club[] =   {"A\5","2\5","3\5","4\5","5\6","6\5","7\5","8\5","9\5","10\5","J\5","Q\5","K\5"};
  19.     string spade[] =   {"A\6","2\6","3\6","4\6","5\6","6\6","7\6","8\6","9\6","10\6","J\6","Q\6","K\6"};
  20.  
  21.  
  22.     string general[52] ; //= new string[52];
  23.     int k=0;
  24.  
  25.         for(int j = 0; j <= 12; j++)
  26.         {
  27.               general [k++] = heart[rand()% 12];
  28.               general [k++] = diamond[rand()% 12];
  29.               general [k++] = club[rand()% 12];
  30.               general [k++] = spade[rand()% 12];
  31.         }
  32.  
  33.  
  34.   int id1, id2;  
  35.   string temp;
  36.   for (int i = 0; i < 100; i++ )
  37.   {
  38.       id1 = rand()%52;
  39.       id2 = rand()%52;
  40.       if(id1!=id2)
  41.       {
  42.       temp = general[id1];
  43.       general[id1] = general[id2];
  44.       general[id2] = temp;
  45.       }
  46.  
  47.  }
  48.  for(int i=0; i<52; i++)
  49.  {
  50.  
  51. cout<< general[i]<<"  ";
  52. }
  53. cout << endl;
  54.  
  55.  
  56. int currentId = 1;
  57. string player1 [5];
  58. string player2 [5];
  59. int currentindex =0;
  60. for (int p = 0; p < 5; p++)
  61.     {
  62.  
  63.          player1 [p] = general [currentindex]; // picks the 0th,2nd,4th,6th,8th elements
  64.  
  65.          player2 [p] = general [currentId]; // picks the 1st,3rd,5th,7th,9th elements 
  66.          currentindex = currentindex + 2;
  67.          currentId = currentId +2;
  68.     }
  69.  
  70.     for (int z = 0;z < 5;z++)
  71.     {
  72.     cout << player1[z] <<endl;
  73. }
  74. cout <<"-------------------------------"<<endl;    
  75.  
  76. for (int t = 0; t< 5; t++)
  77. cout <<player2[t]<<endl;
  78.  
  79.  
  80.  
  81. system("pause");
  82.  
  83.  return 0;
  84. }
Mar 16 '07 #1
3 3061
DeMan
1,806 Top Contributor
There are many approaches to this problem.....

One would be to "empty" an arrays value once it has been chosen, and set a loop around the random number generator which only exits when it finds an non-empty spot. This can, however be a little tedious and expensive.

ANother idea, might be to have a list where you keep all of the cards in some order (point to the array entry you want from the element in the list). As you choose a random card, remove it from the list, and alter your random number generator to choose a random number over the size of the reamining list eg:

if I have 10 elements in a list
Then rand % 10 and remove the element.

I now have nine elements in the list so rand % 9

etc.
Mar 16 '07 #2
Ganon11
3,652 Recognized Expert Specialist
If you can use classes, I would recommend making a Card class to hold the suit and value, and a Deck class to hold 52 cards. You can write functions in the Deck class to select a card from the top of the deck and remove that card from the current list of cards - this will guarantee that you on't get a repeat of a card.
Mar 16 '07 #3
Savage
1,764 Recognized Expert Top Contributor
I'm trying to shuffle a deck of card in C ++, with out having the same card twice. And I'm supposed to give each player 5 cards. And if they want, they can replace 3 cards. Right now I can assign 5 cards to each player, but some of the cards repeat themselces (ex. I have 3 Ace of spades, or 2 king of clubs, etc). Can anyone help me fix this problem. Here is what I have so far.

Expand|Select|Wrap|Line Numbers
  1. #include <iostream> 
  2. #include <ctime> 
  3. #include <cstdlib>
  4. #include <cmath>
  5.  
  6.  
  7. using namespace std;
  8. using std::cout;
  9. using std::strncpy;
  10.  
  11. //int random;
  12.  
  13. int main() 
  14.    srand((unsigned)time(0));
  15.  
  16.     string  heart[] =  {"A\3","2\3","3\3","4\3","5\3","6\3","7\3","8\3","9\3","10\3","J\3","Q\3","K\3"};
  17.     string diamond[] = {"A\4","2\4","3\4","4\4","5\4","6\4","7\4","8\4","9\4","10\4","J\4","Q\4","K\4"};
  18.     string  club[] =   {"A\5","2\5","3\5","4\5","5\6","6\5","7\5","8\5","9\5","10\5","J\5","Q\5","K\5"};
  19.     string spade[] =   {"A\6","2\6","3\6","4\6","5\6","6\6","7\6","8\6","9\6","10\6","J\6","Q\6","K\6"};
  20.  
  21.  
  22.     string general[52] ; //= new string[52];
  23.     int k=0;
  24.  
  25.         for(int j = 0; j <= 12; j++)
  26.         {
  27.               general [k++] = heart[rand()% 12];
  28.               general [k++] = diamond[rand()% 12];
  29.               general [k++] = club[rand()% 12];
  30.               general [k++] = spade[rand()% 12];
  31.         }
  32.  
  33.  
  34.   int id1, id2;  
  35.   string temp;
  36.   for (int i = 0; i < 100; i++ )
  37.   {
  38.       id1 = rand()%52;
  39.       id2 = rand()%52;
  40.       if(id1!=id2)
  41.       {
  42.       temp = general[id1];
  43.       general[id1] = general[id2];
  44.       general[id2] = temp;
  45.       }
  46.  
  47.  }
  48.  for(int i=0; i<52; i++)
  49.  {
  50.  
  51. cout<< general[i]<<"  ";
  52. }
  53. cout << endl;
  54.  
  55.  
  56. int currentId = 1;
  57. string player1 [5];
  58. string player2 [5];
  59. int currentindex =0;
  60. for (int p = 0; p < 5; p++)
  61.     {
  62.  
  63.          player1 [p] = general [currentindex]; // picks the 0th,2nd,4th,6th,8th elements
  64.  
  65.          player2 [p] = general [currentId]; // picks the 1st,3rd,5th,7th,9th elements 
  66.          currentindex = currentindex + 2;
  67.          currentId = currentId +2;
  68.     }
  69.  
  70.     for (int z = 0;z < 5;z++)
  71.     {
  72.     cout << player1[z] <<endl;
  73. }
  74. cout <<"-------------------------------"<<endl;    
  75.  
  76. for (int t = 0; t< 5; t++)
  77. cout <<player2[t]<<endl;
  78.  
  79.  
  80.  
  81. system("pause");
  82.  
  83.  return 0;
  84. }
You need to implement a do while loop in your for loop for generarting cards.the loop shoul serch your's arrays and reapet it self if the same card is generated

It should be like:

Expand|Select|Wrap|Line Numbers
  1. int card_type[12];
  2. do{
  3.             k=0;
  4.             for(int j = 0; j <= 12; j++)
  5.             {
  6.                   card_type[j] = rand()%12;
  7.                   general [k++] = heart[card_type[j]];
  8.                   general [k++] = diamond[card_type[j]];
  9.                   general [k++] = club[card_type[j]];
  10.                   general [k++] = spade[card_type[j]];
  11.              }  
  12.  
  13.      }while( card_type[0]==card_type[1] ............);

Savage
Mar 16 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

23
12963
by: JC | last post by:
I am very new to programming and learning on my own. Why do I keep getting duplicate values using this code? I want to shuffle a deck of 52 cards. The logic seems right to me. Randomize For C = 0 To 1000 C1 = Cards(Int(Rnd * 52)) ' returns a number from 0 to 51
16
2126
by: glowfire | last post by:
Please, somebody help me with this program! We have a deck of 52 cards and we shuffle the deck by choosing a random card out of the deck placing it back in the deck at some random place. Repeat it 500 times and then consider the deck shuffled. Choose a hand of 5 cards from the top of the deck. Count the number of hands which have three-of-a-kind but don't count hands which have four-of-a-kind. Continue to draw new hands until the deck...
6
6224
by: CaseyB | last post by:
If I wanted to create a game like Solitaire that would first randomly shuffle a deck of cards, I figured out that all I had to use is the Random() class or rnd and make sure I use the Randomize function so as not to get the same card twice. BUT I noticed that some Solitaire games allow you to select one of the 4,294,967,296 possibilities in a 52 card deck. I want to do something similar, after I shuffle the deck I want to show the number...
8
5560
by: ericvw | last post by:
How would I shuffle a static array of 52 cards that you input an integer, n, into a function and it takes the first n cards as the left segment and the remaining as the right. Then it shuffles this deck starting from the first of the right segment, then first of the left, second of the right, second of the left. Once one side is exhausted it fills in the rest of the shuffle with the other remaining segment. Any suggestions?
22
5267
by: greenflame | last post by:
I would like to make a function that takes a list, more specificaly a list of strings, and shuffles its elements, like a pile of cards. The following is a script I tryed to make that implements pile shuffling. ---------- testdeck = list('qwertyuiop') def pileshuffle(DECK, NUMPILES): """Split the deck given into NUMPILES piles. Then also put the piles""" \
10
4968
by: Arun Nair | last post by:
Can any one help me with this im not getting it even after reading books because there is not much of discussion anywhere a> Implement a calss that represents a playing card. The class should implement the following methods: _ _ init _ _ (self, rank, suit) Creates a card. rank is an integer in range of 1 to 13 (Ace:1, King 13), suit is a character in set {'h','d','c','s'} getRank(self) Returns the rank of the card
4
9195
by: Pratik | last post by:
For the time being, I'm doing a simple swap method for my deck of cards using the random number generator in cstdlib. I've created a dynamic array of a type class Card. When I go to shuffle it and then later print the shuffled deck, some of the values overlap -- I can't figure out why. Here's my code: void shuffle() { for (counter = 0; counter < 120; counter++) {
8
29172
by: garyrowell | last post by:
I have been at this programme for hours trying to work out what is wrong. Any help would be very much appricated. Here is the breif I received. The program This week you are going to write three classes: Card.java, Deck.java and DeckTester.java. The specification for each class is given below. Card.Java This is a simple class that represents a playing card. Card has two attributes: • rank which is a String that represents the value...
1
2393
by: Vneha | last post by:
import java.util.*; public class Deck { public static int numSuits = 4; public static int numRanks = 13; public static int numCards = numSuits * numRanks; private Card cards;
0
9719
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9599
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10371
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10111
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9193
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7650
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5546
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5684
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3010
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.