Search code examples
c#textscramble

Scramble & descramble text


I already got this method to scramble my text but I have no clue on how to unscramble it.

string input = "https://www.google.de/";
char[] chars = input.ToArray();
Random r = new Random(259);
for (int i = 0; i < chars.Length; i++)
{
    int randomIndex = r.Next(0, chars.Length);
    char temp = chars[randomIndex];
    chars[randomIndex] = chars[i];
    chars[i] = temp;
}
new string(chars);

Console.WriteLine(chars);
Console.ReadKey();

How can I make a scramble or shuffle function that shuffles the text with a specific number so it scrambles the text the same way every time and how can I unshuffle it after that?


Solution

  • Just do the same thing you already did backwards (you need to use the same random numbers from the same seed in reverse order, so get those in a list first):

            string input = "https://www.google.de/";
            char[] chars = input.ToArray();
            Random r = new Random(259);
            for (int i = 0; i < chars.Length; i++)
            {
                int randomIndex = r.Next(0, chars.Length);
                char temp = chars[randomIndex];
                chars[randomIndex] = chars[i];
                chars[i] = temp;
            }
            string scrambled = new string(chars);
    
            Console.WriteLine(chars);
            Console.ReadKey();
    
            r = new Random(259);
            char[] scramChars = scrambled.ToArray();
            List<int> swaps = new List<int>();
            for (int i = 0; i < scramChars.Length; i++)
            {
                swaps.Add(r.Next(0, scramChars.Length));
            }
            for (int i = scramChars.Length - 1; i >= 0; i--)
            {
                char temp = scramChars[swaps[i]];
                scramChars[swaps[i]] = scramChars[i];
                scramChars[i] = temp;
            }
    
            string unscrambled = new string(scramChars);
    
            Console.WriteLine(scramChars);