#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;
int rand_0toN1(int n);
void draw_a_card();
int select_next_available(int n);
char *suits[4] ={"hearts","diamonds","spades","clubs"};
char *ranks[13]={"ace","two","three","four","five","six","seven","eight",
"night","ten","jack","queen","king"};
bool card_drawn[52];
int cards_remaining=52;
int main() {
int n,i;
srand(time(NULL));
while(true){
cout<<"Enter no. of cards to draw";
cout<<"(0 to exit): ";
cin>>n;
if(n==0)
{
cout<<n<<endl;
break;
}
for(i=1;i<=n;i++)
draw_a_card();
}
return 0;
}
void draw_a_card(){
int r;
int s;
int card,n;
if(cards_remaining == 0){
cout<<"Reshufing."<<endl;
cards_remaining=52;
for(int i = 0;i<52;i++)
card_drawn[i]=false;
}
n=rand_0toN1(cards_remaining--);
card=select_next_available(n);
r=card % 13;
s=card / 13;
cout<<ranks[r]<<" of "<<suits[s]<<endl;
}
int select_next_available(int n){
int i=0;
while(card_drawn[i])
{
i++;
}
while(n-->0){
i++;
while(card_drawn[i])
i++;
}
card_drawn[i]=true;
return i;
}
int rand_0toN1(int n){
return rand() % n;
}
一个模拟抽牌的过程
转载于:https://my.oschina.net/ruochenchen/blog/129016