Swapping string elements

New to C++. I need help writing a function that will swap characters' positions in the following string randomly. Any ideas?

String
 
const string s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,' ";


Random seed function
1
2
3
4
5
6
7
8
9
string create_permutation(unsigned seed)
{
	cout << "Input seed" << endl;
	cin >> seed;
	srand(seed);
	string permutation = ALPHABET;
	random_shuffle(permutation.begin(), permutation.end());
	return permutation;
}


Thanks for any assistance offered.
What's the problem? create_permutation shouldn't seed every time. In fact, I'd create static PRNGs, and use the ones from C++11. If you google random_shuffle, you'll get examples.
The issue is that the function shouldn't just rearrange the string, but 'swap' character pairs.

E.g. A=X, X=A, F=J, J=F, S=W, W=S, etc.
Ah. That wasn't clear for me.

Okay then. There are many ways to do it, but I think that this one is natural and quite simple:

Create a list of numbers from 0 to N, where N is the last position of string. Let's call this list L.
Now randomly choose a pair of numbers X and Y, X != Y, from the range of [0,length(L)-1]. Swap elements at position L[X] and L[Y]. Remove items at position X and Y. Remember to start from the greater, because list will shrink. Do so, unless you've got <2 elements in the list L. The algorithm is finished.

I'd use a vector for list L, with your own removal function: see this post: http://stackoverflow.com/questions/9218724/get-random-element-and-remove-it .

I only came up with the algorithm, and not tested it, so it might be buggy. Please let me know whether this works.

PS. Alternatively you can put elements to the list L(which we know is vector), shuffle it, and just grab pairs of numbers from the back; the outcome is the same. I don't know about the efficency, but it looks like it's simple too.
Last edited on
Topic archived. No new replies allowed.