Using Random Shuffle
Sep 9, 2014 at 4:22pm UTC
I need to make this program that will scramble the letters between the first and last letter of each word randomly. I want to use random_shuffle but I cannot figure out how to use it.
The output would be something like, "I lvoe cmoupetr sicnece"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str = "I love computer science\n\n" ;
string str1 = str.substr(0, 1);
string str2 = str.substr(2, 4);
string str3 = str.substr(7, 8);
string str4 = str.substr(16, 7);
cout << "\n\nbefore the random: " << str2; //before love is shuffled
random_shuffle(0, 3); //how do I use this?
cout << "\n\nafter the random: " << str2 << endl; //after love is shuffled
system("pause" );
return 0;
}
Sep 9, 2014 at 4:39pm UTC
random_shuffle takes as argument iterators to the beginning and end of the sequence that you want to shuffle.
To shuffle the characters in str2 you can do
random_shuffle(str2.begin(), str2.end());
Sep 9, 2014 at 4:39pm UTC
random_shuffle takes two iterators. One to the beginning element to be shuffled and an iterator past the last element to be shuffled.
random_shuffle (str2.begin(), str2.end());
Sep 9, 2014 at 7:43pm UTC
Topic archived. No new replies allowed.