Open In App

How to Shuffle a Vector in C++?

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Shuffling a vector means rearranging the position of its elements in random order. In this article, we will learn how to shuffle the vector in C++.

The most efficient way to shuffle a vector is by using shuffle() method.  Let’s take a look at an example:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4, 5, 6, 7};

    // Initialize random number generator
    random_device rd;
    mt19937 g(rd());

    // Shuffle the vector
    shuffle(v.begin(), v.end(), g);

    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
3 7 4 2 1 5 6 

Explanation: The shuffle() function uses random number generator to determine new positions for the elements in the range. Here, mt19937 generator is used.

There are also some other methods in C++ to shuffle a vector. Some of them are as follows:

Using random_shuffle()

The random_shuffle() function is similar to above method, but the random number generator of this function is not efficient as based on rand() function.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4, 5, 6, 7};

    // Shuffle the vector
    random_shuffle(v.begin(), v.end());

    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
5 4 2 7 1 6 3 

Using Fisher-Yates Shuffle Algorithm

The Fisher-Yates shuffle algorithm can also shuffle the vector manually by iterating from last to first element in vector and using a random number generator to select elements to be swapped.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4, 5, 6, 7};

    // Shuffle the vector
    for (int i = v.size() - 1; i >= 0; i--) {
      
        // Generate the random index 
        int j = rand() % (i + 1);
        swap(v[i], v[j]);
    }

    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
1 7 6 4 3 5 2 

Explanation: In this method, we are iterating the vector from last to first element and generate the random index at every index of vector and swap the current index element with the generated random index element.

Using Permutation

In this method, we randomly generate the permutation of vector using functions like next_permutation() until a random one is found. This method is not efficient for large vectors due to factorial growth in permutations.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4, 5, 6, 7};

    // Generate the permutation of vector
    do {
      
        // Shuffle the vector
        random_shuffle(v.begin(), v.end());
    } while (!next_permutation(v.begin(), v.end()));

    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
5 4 2 7 3 1 6 

Next Article
Practice Tags :

Similar Reads