Character Shuffler

梦想与她 提交于 2019-12-12 16:27:20

问题


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:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3226877/character-shuffler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!