-
April 27th, 2010, 01:10 PM
#1
Problems with random generation and counting
The problem is to have the computer is picking individual cards from a full deck that is shuffled after each pick (therefore cards can be picked more than once)
The Goal is to end up with one card of each suit, and to tell the user how many picks it took
Sample output:
Queen of Spades
5 of Clubs
Queen of Hearts
4 of Diamonds
Number of Picks: 12
So far, i have been able to generate 4 random cards, but am unable to convince the program to stop and reset for the next card,
In addition, the counter for the number of picks is presenting problems.
Thank you for any suggestions, and my code is below (compiled in Visual C++ 2008 express edition)
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
const int Cards = 52;
// Shuffle the elements in an array
void shuffle(int list[], int size)
{
srand(time(0));
for (int i = 0; i < size; i++)
{
// Generate an index randomly
int index = rand() % Cards;
int temp = list[i];
list[i] = list[index];
list[index] = temp;
}
}
int main()
{
int deck[Cards];
const string suits[] = {"Clubs", "Diamonds", "Hearts", "Spades"};
const string ranks[] = {"Ace", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "Jack", "Queen", "King"};
// Initialize cards
for (int i = 0; i < Cards; i++)
deck[i] = i;
// Shuffle the cards
shuffle(deck, Cards);
// Display cards
//Card 1
for (int i = 0; i < 1; i++)
{
cout << ranks[deck[i] % 13] << " of "
<< suits[deck[i] / 13] << endl;
}
//Card 2
for (int i = 1; i < 2; i++)
{
cout << ranks[deck[i] % 13] << " of "
<< suits[deck[i] / 13] << endl;
}
//Card 3
for (int i = 2; i < 3; i++)
{
cout << ranks[deck[i] % 13] << " of "
<< suits[deck[i] / 13] << endl;
}
//Card 4
for (int i = 3; i < 4; i++)
{
cout << ranks[deck[i] % 13] << " of "
<< suits[deck[i] / 13] << endl;
}
return 0;
}
-
April 27th, 2010, 01:11 PM
#2
Re: Problems with random generation and counting
Common mistake. Never call srand() more than once in a program. Just stick it at the top of main(), and don't call it anywhere else.
-
April 27th, 2010, 01:21 PM
#3
Re: Problems with random generation and counting
With the current code, the result is 4 random cards, however, im still having trouble telling the program that once it finds one particular suit, to reshuffle the deck and find another separate suit, while still counting! and i will fix the srand()
Thanks!
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|