您的位置:首页 > 编程语言 > C语言/C++

C++实践参考:洗牌

2016-06-22 16:04 316 查看
/*
*Copyright(c)2016.烟台大学计算机学院
*All right reserved.
*文件名称:test.cpp
*作者:黄金婵
*完成日期:2016年6月22日
*版本号:v1.0
*
*问题描述:在扑克牌游戏中,每次游戏开始都要求把54张牌重新排列一下,称为洗牌。试编写程序将一副扑克牌(用54个整数1~54表示)随机洗好后,顺序输出54张牌的情况。
*程序输入:
*程序输出:
*/
#include <ctime>
#include <vector>
#include <list>
#include <iostream>
#include <iterator>
#include <cstdlib>
using namespace std;

using namespace std;
typedef vector<int> IntVector;
typedef unsigned int VIndex;
void vectorShuffle(IntVector &unshuffled,IntVector &shuffled)
{
VIndex p,size=unshuffled.size();
while(size)
{
p=rand()%size--;
shuffled.push_back(unshuffled[p]);
unshuffled.erase(unshuffled.begin()+p);
}
}

int main()
{
ostream_iterator<int> os(cout," ");
srand(time(NULL));
IntVector c,sc;
for(VIndex i=1; i<=54; i++)
{
c.push_back(i);
}
cout<<"Before Shuffle"<<endl;
copy(c.begin(),c.end(),os);
cout<<endl;
vectorShuffle(c,sc);
cout<<"\nAfter Shuffled"<<endl;
copy(sc.begin(),sc.end(),os);
cout<<endl<<endl;
return 0;
}




知识点总结:

原数组的第 i 个元素在新数组的前 i 个位置的概率都是:(1/i) * [i/(i+1)] * [(i+1)/(i+2)] *...* [(n-1)/n] = 1/n,(即第i次刚好随机放到了该位置,在后面的n-i 次选择中该数字不被选中)原数组的第 i 个元素在新数组的 i+1 (包括i + 1)以后的位置(假设是第k个位置)的概率是:(1/k) * [k/(k+1)] * [(k+1)/(k+2)] *...* [(n-1)/n] = 1/n(即第k次刚好随机放到了该位置,在后面的n-k次选择中该数字不被选中)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: