I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com

random_shuffle

Brings the elements into a random order
+ View version details

Key Facts

Gyroscopic Couple: The rate of change of angular momentum (\inline \tau) = \inline I\omega\Omega (In the limit).
  • \inline I = Moment of Inertia.
  • \inline \omega = Angular velocity
  • \inline \Omega = Angular velocity of precession.


Blaise Pascal (1623-1662) was a French mathematician, physicist, inventor, writer and Catholic philosopher.

Leonhard Euler (1707-1783) was a pioneering Swiss mathematician and physicist.

Definition

The random_shuffle() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.

Interface

#include <algorithm>
template < class RandomAccessIterator >
   void random_shuffle(
      RandomAccessIterator first, 
      RandomAccessIterator last
   );
template < class RandomAccessIterator, class RandomNumberGenerator >
   void random_shuffle(
      RandomAccessIterator first, 
      RandomAccessIterator last, 
      RandomNumberGenerator& rand
   );

Parameters:
Parameter Description
first A random-access iterator addressing the position of the first element in the range to be rearranged
last A random-access iterator addressing the position one past the final element in the range to be rearranged
rand A special function object called a random number generator

Description

Random_shuffle function reorders the elements of a range by putting them at random places.

The first version uses an internal random number generator, and the second uses a Random Number Generator, a special kind of function object, that is explicitly passed as an argument.

Return Value

None.

Complexity

The complexity is linear; performs as many calls to swap as the length of the range [first,last) - 1.
Example:
Example - random_shuffle algorithm
Problem
This program illustrates the use of the STL random_shuffle() algorithm (default version) to randomize the order of values in a vector of integers.
Workings
#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 <<"\nHere are the values in the vector:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";
 
  cout << "\nNow we randomize the order of the values.";
  random_shuffle(v.begin(), v.end());
 
  cout <<"\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;
}
Solution
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:
9 2 10 3 1 6 8 4 5 7
References