Can I restore a random_shuffle on a string?

I was wondering if the following random_shuffle could be reversed?
ie; restore the alphabet to its original string arrangement after being passed to a different function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

void restore(string alphabet);

int main(int argc, char *argv[])
{
     string alphabet = "abcdefghijklmnopqrstuvwxyz";
       random_shuffle( alphabet.begin(), alphabet.end() );
        cout << "alphabet after shuffling: " << alphabet << endl;
	 restore(alphabet);
cin.ignore().get();
 return 0;
}

void restore(string alphabet)
{
	cout << alphabet<<endl;


}
Yes, by storing the original string in a different variable and assigning that one to alphabet after each call (or vice versa).
Yeah know what you mean. But I was wanting to pass it without any original string attached. Sort of like an encryption I guess.
I suppose what I am wanting to know is whether (*warning* possibly stupid question) , whether
I could somehow get the particular algorithm that randomly shuffled alphabet in that
particular instance and pass that into the restore function?? And then use that algorithm to restore the string?? Possible? Or am I in some fantasy realm of C++++++++ ?
No, it can be done. Look up the implementation of random_shuffle. One possible implementation can be seen here:
http://www.cplusplus.com/reference/algorithm/random_shuffle/

So if you call srand before random_shuffle and then call srand again with the same seed and generate the necessary amount of random numbers and then do the swaps in reverse order, you'll get the original string.
Last edited on
Okay thanks Athar.

call srand again with the same seed and generate the necessary amount of random numbers and then do the swaps in reverse order, you'll get the original string.


Possibly out of my league...
Just split my sentences into several shorter ones and it might appear much simpler.
You just need to go through the random_shuffle loop in reverse order and provide a function object that hands out the previously generated random numbers in reverse order.
How is it possible to extract the 'seed' integer value as initially generated algorithmically by srand? If I could find a way of doing that then it might be the key, as you stated.
Simplistically, its not possible to cout it, hahaha, I tried it !!!?
I googled same and came up zilch apart from hard coding or number sequencing the srand to get the same result each time, but thats not really what Im after. I think I need to capture the integer value of the seed when its first generated.
srand takes one parameter, which is the seed. You just need to use the same one in both cases.
Last edited on
Right gotcha

Use srand (seed) instead of srand(time(0));
Topic archived. No new replies allowed.