3

我只是想知道是否有一种方法(使用 ASP.NET C#)可以“随机播放”字符串的内容,但仍然可以单击另一个按钮并将其“取消随机播放”回到其原始内容而不保存原始内容?

谢谢 :)

例子:

"This is not shuffled."

"isuo .tffsnl iTh shed"

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

"This is not shuffled."
4

2 回答 2

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.

于 2010-07-12T08:34:13.393 回答
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.

于 2010-07-12T08:32:23.097 回答