做作业时候遇到这个问题,感觉这种算法很快捷
一个洗牌的算法。。多线程没做出来然后放弃了
生成1-52之内的不重复随机数,一个数代表了一张牌,循环52次即摸牌完毕。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
string a[5]={"红桃","方片","黑桃","梅花"};
string b[15]={"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
string c[60]={"0"};
int k=0; //总牌数,初始化为0
srand((int)time(0));
//初始化牌堆
for(int i=0;i<4;i++)
for(int j=0;j<13;j++)
{
c[k]=a[i]+b[j];
k++;
}
//循环计数递减,每抽取一个字符串就将其放到字符串组末尾,从下次循环中剔除
for(int i=k;i>=1;i--)
{
int temp = rand()%i ;
cout<<"第"<<i<<"张:"<<c[temp]<<endl;
swap(c[temp],c[i-1]);
}
return 0;
}