Shuffle vs random_shuffle in C++


Here we will see the Shuffle and random_shuffle in C++. Let us see the random_shuffle first. It is used to randomly rearrange the elements in range [left, right). This function randomly swaps the positions of each element with the position of some randomly chosen positions.

We can provide some random generator function to tell which element will be taken in every case. If we do not provide some, it will use its own random generator function.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int myRandomGenerator(int j) {
   return rand() % j;
}
main() {
   srand(unsigned(time(0)));
   vector<int> arr;
   for (int j = 1; j < 20; ++j) //generate 20 numbers and add them into vector arr
      arr.push_back(j);
   random_shuffle(arr.begin(), arr.end()); //use inbuilt random function to shuffle
   cout << "arr elements:";
   for (vector<int>::iterator i = arr.begin(); i != arr.end(); ++i)
      cout << ' ' << *i;
   cout << endl;
   // using myRandomGenerator
   random_shuffle(arr.begin(), arr.end(), myRandomGenerator);
   cout << "arr elements:";
   for (vector<int>::iterator i = arr.begin(); i != arr.end(); ++i)
      cout << ' ' << *i;
   cout << endl;
}

Output

arr elements: 5 14 15 6 3 16 13 12 10 2 4 1 17 9 18 11 7 8 19
arr elements: 8 10 5 6 14 1 15 3 19 16 13 18 7 9 4 12 11 17 2

Now let us see what is the shuffle() function. This is also used to rearrange elements in range [left, right). randomly. It takes one uniform random number generator.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
main() {
   vector<int> arr;
   unsigned seed = 0;
   for (int j = 1; j < 20; ++j) //generate 20 numbers and add them into vector arr
      arr.push_back(j);
   shuffle(arr.begin(), arr.end(), default_random_engine(seed));
   cout << "arr elements:";
   for (vector<int>::iterator i = arr.begin(); i != arr.end(); ++i)
      cout << ' ' << *i;
   cout << endl;
}

Output

arr elements: 19 7 5 6 12 4 13 3 1 17 11 14 18 2 8 15 9 10 16

The only difference between random_shuffle() and shuffle() is that, the random_shuffle() uses rand() function to generate random indices, and shuffle() uses uniform random number generator. Though, if we pass uniform random number generator with the random_shuffle(), then it will generate same kind of results.

Updated on: 30-Jul-2019

320 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements