3

I was just wondering if there's a way (using ASP.NET C#) to "shuffle" up the contents of a string, but still be able to click another button and "UNshuffle" it back to its original content withOUT saving the original content?

Thank you :)

Example:

"This is not shuffled."

"isuo .tffsnl iTh shed"

...And then I click the "UNShuffle" button and it becomes normal again:

"This is not shuffled."
  • 1
    @j-t-s, `public int Random() { return 4; }`, no you cannot shuffle them Randomly and then get it back to the original state without saving any meta-data. But if you know Exactly how the characters are moved you can move them back again.. – Filip Ekberg Jul 12 '10 at 08:32

2 Answers2

8

The suffling is easy:

var rnd = new Random();
string unsuffled = "This is not shuffled.";
string shuffled = new string(unsuffled.OrderBy(r => rnd.Next()).ToArray());

But as it is random you cannot unshuffle unless you store the previous string or the mapping.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • So, if I store the Random(); and then just use the reference to the stored random when I go to unshuffle, that should do it, right? [thank you] –  Jul 12 '10 at 08:38
  • 2
    Nope you would have to store either the seed you used to make your random (and make a new instance with it) or store the random values you got from your random instance. Even then I can't think of how you would know the original order. – Matt Mitchell Jul 12 '10 at 08:43
6

Well, you'd need to save something. One simple idea:

  • Use a random number generator to generate a random seed.
  • Create a new instance of Random to use for shuffling using that seed
  • Shuffle with a modified Fisher-Yates shuffle
  • Keep hold of the seed

The shuffle is then reversible - admittedly with a bit of effort. (I'd probably shuffle the numbers 0...(n-1) in the same way, and then reverse map the characters that way.)

The tricky bit is that you do need the seed - it's a bit like a salt in a stored password hash. You've got to have some extra bit of information to say how it was shuffled otherwise you won't know whether "abc" came from "bac" or "cab" for example.

Steve Weet
  • 28,126
  • 11
  • 70
  • 86
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    If the shuffle only needs to seem random then you can calculate a seed from the shuffled text and you would not need to store a seed. Using something like the sum of the ASCII values of the individual characters of the (un)shuffled string should do the trick. – Cornelius Jul 12 '10 at 08:49
  • 1
    @j-t-s: So are you okay with the same input always being "shuffled" to the same output? – Jon Skeet Jul 12 '10 at 08:53