Algorithm Random Shuffle Function - C++ Programming Tutorial
C++ Course / STL Algorithm / Algorithm Random Shuffle Function

Algorithm Random Shuffle Function

BLUF: Mastering Algorithm Random Shuffle Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Algorithm Random Shuffle Function

C++ is renowned for its efficiency. Learn how Algorithm Random Shuffle Function enables low-level control and high-performance computing in the tutorial below.

The random_shuffle function in C++ rearranges the elements within a specified range by placing them in random positions.

The initial iteration employs an internal random number generator, while the subsequent iteration utilizes a random number generator that functions as a unique type of function object passed explicitly as an argument.

Syntax

Example

generator by default (1)	

template <class RandomAccessIterator>
                 void random_shuffle (RandomAccessIterator first, RandomAccessIterator last);

specific generator (2)
	
template <class RandomAccessIterator, class RandomNumberGenerator>
  void random_shuffle (RandomAccessIterator first, RandomAccessIterator last,
                       RandomNumberGenerator& gen);

Parameter

A random access iterator indicating the location of the initial element in the range that is to be reorganized.

last: A random access iterator indicating the position immediately following the last element within the range intended for reorganization.

An output iterator indicating the location of the initial element within the target range.

A distinctive function object known as a random number generator.

Return value

Complexity

The complexity increases linearly within the specified range [first, last) when generating random values and performing element swaps.

Data races

The elements within the range [first, last) are altered.

The items within the range from the result to the value that is returned have been modified.

Exceptions

This function will raise an exception if any of the random number generation, element swapping, or iterator operation triggers an exception.

Please be aware that providing incorrect parameters can result in unpredictable behavior.

Example 1

Let's explore a straightforward example to illustrate the usage of random_shuffle:

Example

#include <iostream>
#include <vector> 
#include <algorithm>
#include <numeric>
#include <iterator>

using namespace std;

int main() {
  vector<int> v(10); 
  iota(v.begin(), v.end(), 0);  //generating a value from 0-9

  cout << "before: ";
  copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
  cout << endl;

  random_shuffle(v.begin(), v.end());

  cout << " after: ";
  copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
  cout << endl;
  
  return 0;
}

Output:

Output

before: 0 1 2 3 4 5 6 7 8 9 
after: 4 3 7 8 0 5 2 1 6 9

Example 2

Let's see another simple example:

Example

#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;
 
int main()
{
  int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  vector<int> v(a, a+10);
 
  cout <<"Here are the values in the vector:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";
 
  cout << "\n\nNow we randomize the order of the values.";
  random_shuffle(v.begin(), v.end());
 
  cout <<"\n\nHere are the revised contents of the vector:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";
 
  return 0;
}

Output:

Output

Here are the values in the vector:
1 2 3 4 5 6 7 8 9 10 

Now we randomize the order of the values.

Here are the revised contents of the vector:
5 4 8 9 1 6 3 2 7 10

Example 3

Let's see another simple example:

Example

#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
using namespace std;
 
void print(vector <string> vs)
{   
    vector <string>::iterator i;
    for(i = vs.begin(); i != vs.end(); i++)
    {
        cout << setw(2) << *i << "  ";
    }
    cout << endl;
}
 
int main()
{
    string s[] = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
    vector <string> vs(s, s + 13);
 
    cout << "Original order : ";
    print(vs);
    cout << "Shuffling cards in uniformly random order ... "
         << endl;
    random_shuffle(vs.begin(), vs.end());
    cout << "Pick any three cards ... " << endl;
    cout << "You have got   : ";
    cout << vs.back() << ", ";
    vs.pop_back();
    cout << vs.back() << ", ";
    vs.pop_back();
    cout << vs.back() << endl;
    vs.pop_back();
    
    return 0;
}

Output:

Output

Original order :  A   2   3   4   5   6   7   8   9  10   J   Q   K  
Shuffling cards in uniformly random order ... 
Pick any three cards ... 
You have got   : 9, 8, 4

Example 4

Let's see another simple example:

Example

#include <iostream>     // std::cout
#include <algorithm>    // std::random_shuffle
#include <vector>       // std::vector
#include <ctime>        // std::time
#include <cstdlib>      // std::rand, std::srand

using namespace std;

// random generator function:
int myrandom (int i) { return rand()%i;}

int main () {
  srand ( unsigned ( time(0) ) );
  vector<int> myvector;

  // set some values:
  for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9

  // using built-in random generator:
  random_shuffle ( myvector.begin(), myvector.end() );

  // using myrandom:
  random_shuffle ( myvector.begin(), myvector.end(), myrandom);

  // print out content:
  cout << "myvector contains:";
  for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    cout << ' ' << *it;

  cout << '\n';

  return 0;
}

Output:

Output

myvector contains: 9 7 5 6 3 4 2 8 1

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience