我正在尝试模拟一副牌,但我不知道如何制作它所以它随机选择一张牌但只有一次。我一直在拿双卡。
#include <iostream>
#include <cstdlib> //for rand and srand
#include <cstdio>
#include <string>
using namespace std;
string suit[] = { "Diamonds", "Hearts", "Spades", "Clubs" };
string facevalue[] = { "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Jack", "Queen", "King", "Ace" };
string getcard() {
string card;
int cardvalue = rand() % 13;
int cardsuit = rand() % 4;
card += facevalue[cardvalue];
card += " of ";
card += suit[cardsuit];
return card;
}
int main() {
int numberofcards = 52;
for (int i = 0; i < numberofcards; i++) {
cout << "You drew a " << getcard() << endl;
}
system("pause");
}
有什么建议吗?
答案 0 :(得分:4)
它是一副纸牌。就这样做:
nextCard
索引初始化到您的套牌中来启动绘图循环。每次“抽奖”(deck[nextCard]
处的卡片)将nextCard
提前一个。当nextCard
== 52时,你就没有了。以下是如何设置卡座的示例。我将nextCard
索引和绘图算法留给您。
#include <iostream>
#include <algorithm>
using namespace std;
// names of ranks.
static const char *ranks[] =
{
"Ace", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Jack", "Queen", "King"
};
// name of suites
static const char *suits[] =
{
"Spades", "Clubs", "Diamonds", "Hearts"
};
void print_card(int n)
{
cout << ranks[n % 13] << " of " << suits[n / 13] << endl;
}
int main()
{
srand((unsigned int)time(NULL));
int deck[52];
// Prime, shuffle, dump
for (int i=0;i<52;deck[i++]=i);
random_shuffle(deck, deck+52);
for_each(deck, deck+52, print_card);
return 0;
}
甲板垃圾场的样本如下:
Seven of Diamonds
Five of Hearts
Nine of Diamonds
Ten of Diamonds
Three of Diamonds
Seven of Clubs
King of Clubs
Five of Diamonds
Ace of Spades
Four of Spades
Two of Diamonds
Five of Clubs
Queen of Diamonds
Six of Spades
Three of Hearts
Ten of Spades
Two of Clubs
Ace of Hearts
Four of Hearts
Four of Diamonds
Ace of Diamonds
Six of Diamonds
Jack of Clubs
King of Spades
Jack of Diamonds
Four of Clubs
Eight of Diamonds
Queen of Hearts
King of Hearts
Ace of Clubs
Three of Spades
Two of Spades
Six of Clubs
Seven of Hearts
Nine of Clubs
Jack of Hearts
Nine of Hearts
Eight of Clubs
Ten of Clubs
Five of Spades
Three of Clubs
Queen of Clubs
Seven of Spades
Eight of Spades
Ten of Hearts
King of Diamonds
Jack of Spades
Six of Hearts
Queen of Spades
Nine of Spades
Two of Hearts
Eight of Hearts
答案 1 :(得分:2)
您需要模拟一副牌,这样当选择一张牌时,它就会从一张牌中删除。
所以会发生什么是你从一个完整的牌组开始然后当你从列表中随机选择一张牌时,你将把它从列表中删除。
答案 2 :(得分:0)
您正在使用替换品进行抽样,这意味着一旦您选择了卡片,您就会将其留在卡座中。将其从数据结构中删除,将其从平台中取出。您需要相应地调整随机抽样,方法是将cardvalue
和cardsuit
范围更改为数组/向量的长度/任何更改。