RaINi RaINi - 1 month ago 31
C# Question

C# 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();


Im not that good at these type of things with number and calculations and such thing would be nice if some one can help me.

I already searched for Functions but i couldnt find one with an example that i understand.

//Edit:

-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?

Answer

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);