Write a program to shuffle a pack of cards
The approach:-- Initialize a cards array and set the seed for rand based on time.
- For each array index generate a random index and swap the elements.
- Output the cards array.
C++ program to shuffle a pack of cards
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { int cards[52]; srand(time(0)); for ( int i = 0; i < 52; i++ ) { cards[i] = i + 1; } for ( int i = 0; i < 52; i++ ) { int index = rand() % 52; int tmp = cards[i]; cards[i] = cards[index]; cards[index] = tmp; } for ( int i = 0; i < 52; i++ ) { cout << cards[i] << " "; } cout << endl; return 0; }Output:-
9 16 21 29 23 37 34 15 47 46 4 27 48 12 39 50 11 36 20 24 6 40 30 7 18 32 14 28 26 8 38 19 51 31 49 44 35 3 41 45 1 13 42 25 2 33 52 5 10 22 43 17
0 comments:
Post a Comment