Mar 17, 2022

Shuffle a deck of cards

 #include <iostream>

using namespace std;


//Write a method to shuffle a deck of cards.


void printArray(int a[], int n)

{

    for(int i=0; i<n; i++)

    {

        cout << a[i] << " ";

    }  

    cout << endl;

}

void shuffle(int a[], int n)

{

    for(int i=n-1; i>=1; i--)

    {

        swap(a[i], a[rand()%(i)]);

    }

}

int main() {

// your code goes here

int a[] = {1, 2, 3, 4, 5, 6};

printArray(a, sizeof(a)/sizeof(a[0]));

shuffle(a, sizeof(a)/sizeof(a[0]));

printArray(a, sizeof(a)/sizeof(a[0]));

return 0;

}


Output:
1 2 3 4 5 6 
5 6 2 1 3 4 

No comments: