TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C++ algorithm random_shuffle() function

C++ algorithm random_shuffle() function with c++ tutorial for beginners and professionals with examples on adjacent_find(),any_of(), copy(), copy_if(), count(), count_if(), equal(), find(), find_end(), find_first_of(), find_if(), find_if_not(), for_each() etc.

<< Back to CPP

C++ Algorithm random_shuffle()

C++ Algorithm random_shuffle() reorders the elements of a range by putting them at random places.

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

Syntax

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

first: A random access iterator pointing the position of the first element in the range to be rearranged.

last: A random access iterator pointing the position one past the final element in the range to be rearranged.

result: An output iterator pointing the position of the first element in the destination range.

gen: A special function object called a random number generator.

Return value

None

Complexity

Complexity is linear in the range [first, last): obtain random values and swaps elements.

Data races

The object in the range [first, last) are modified.

The object in the range between result and the returned value are changed.

Exceptions

This function throws an exception if any of random number generations the element swaps or an operation on iterator throws an exception.

Please note that invalid parameters cause an undefined behavior.

Example 1

Let's see the simple example to demonstrate the use of random_shuffle():

#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:

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:

#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:

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:

#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:

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:

#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:

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

Next TopicC++ Algorithm




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf