> For the complete documentation index, see [llms.txt](https://maksimdan.gitbook.io/interview-practice-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://maksimdan.gitbook.io/interview-practice-problems/coding_practice_questions/hard/shuffle.md).

# Shuffle

**17.2 Shuffle:** Write a method to shuffle a deck of cards. It must be a perfect shuffle-in other words, each of the 52! permutations of the deck has to be equally likely. Assume that you are given a random number generator which is perfect.

* I could just create a new deck where each card I take from the deck has the same probability of being chosen.
  * First selection: 1/52
  * Second selection: 1/51 ...
* std already has a shuffle method. In my implementation, I iterate through the deck of cards and swap with any random position, all with equivalent likelihood.

```cpp
void swap(int *a, int *b) {
    int temp = *(a);
    *(a) = *(b);
    *(b) = temp;
}

void shuffle(array<int, 52> &deck) {
    int r;
    for (int i = 0; i < deck.size(); i++) {
        r = rand() % 52;
        swap(deck[i], deck[r]);
    }
}

int main()
{
    srand(time(nullptr));
    array<int, 52> deck;
    for (int i = 0; i < deck.size(); i++) {
        deck[i] = i;
    }

    //random_shuffle(deck.begin(), deck.end());
    //for (auto i : deck) {
    //    cout << i << " ";
    //}
    //cout << endl;

    shuffle(deck);
    for (auto i : deck) {
        cout << i << " ";
    }
    cout << endl;
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/coding_practice_questions/hard/shuffle.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
