Using Random Shuffle

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;
}
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());
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());

Don't forget to seed the PRNG:

1
2
#include <cstdlib>
#include <ctime> 
1
2
3
4
int main()
{
	srand( time( NULL ) );
	...

Or, better yet, use std::shuffle()
http://www.cplusplus.com/reference/algorithm/shuffle/

And use a PRNG better than the default (like the Mersenne Twister. Don't forget to warm it up by pulling some thousand numbers from it first. http://www.cplusplus.com/reference/random/mt19937/).

(Or the Knuth B engine. http://www.cplusplus.com/reference/random/knuth_b/)

Hope this helps.
Topic archived. No new replies allowed.