This C++ program demonstrates the random_shuffle() algorithm. The function random_shuffle() shuffles the elements of a container in a uniformly random manner. The function takes two iterators to the beginning and end of the container as parameters. The program creates a set of cards, randomly shuffles and randomly opens three cards from the set.
Here is the source code of the C++ program which demonstrates the random_shuffle() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to demonstrate the random_shuffle() algorithm
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
using namespace std;
void print(vector <string> vs)
{
vector <string>::iterator i;
for(i = vs.begin(); i != vs.end(); i++)
{
cout << setw(2) << *i << " ";
}
cout << endl;
}
int main()
{
string s[] = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
vector <string> vs(s, s + 13);
cout << "Original order : ";
print(vs);
cout << "Shuffling cards in uniformly random order ... "
<< endl;
random_shuffle(vs.begin(), vs.end());
cout << "Pick any three cards ... " << endl;
cout << "You have got : ";
cout << vs.back() << ", ";
vs.pop_back();
cout << vs.back() << ", ";
vs.pop_back();
cout << vs.back() << endl;
vs.pop_back();
}
$ a.out Original order : A 2 3 4 5 6 7 8 9 10 J Q K Shuffling cards in uniformly random order ... Pick any three cards ... You have got : 9, 8, 4
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Check Programming Books
- Practice Computer Science MCQs
- Apply for Computer Science Internship
- Practice Programming MCQs
- Check Computer Science Books