Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversible shuffle algorithm using a key

How would I code a reversible shuffle algorithm in C# which uses a key to shuffle and can be reversed to the original state?

For instance, I have a string: "Hello world", how can I shuffle it so that later I could be able to reverse the shuffled string back to "Hello world".

like image 409
Tush Avatar asked Aug 22 '10 11:08

Tush


People also ask

How do you shuffle an array in C++?

Shuffle an Array using STL in C++ These are namely shuffle() and random_shuffle(). This method rearranges the elements in the range [first, last) randomly, using g as a uniform random number generator. It swaps the value of each element with that of some other randomly picked element.

Do we have any inbuilt function for shuffling the values of list?

Python3. This is most recommended method to shuffle a list. Python in its random library provides this inbuilt function which in-place shuffles the list.


1 Answers

Here's a simple implementation of what you need (if I got it well):

public static class ShuffleExtensions
{
    public static int[] GetShuffleExchanges(int size, int key)
    {
        int[] exchanges = new int[size - 1];
        var rand = new Random(key);
        for (int i = size - 1; i > 0; i--)
        {
            int n = rand.Next(i + 1);
            exchanges[size - 1 - i] = n;
        }
        return exchanges;
    }

    public static string Shuffle(this string toShuffle, int key)
    {
        int size = toShuffle.Length;
        char[] chars = toShuffle.ToArray();
        var exchanges = GetShuffleExchanges(size, key);
        for (int i = size - 1; i > 0; i--)
        {
            int n = exchanges[size - 1 - i];
            char tmp = chars[i];
            chars[i] = chars[n];
            chars[n] = tmp;
        }
        return new string(chars);
    }

    public static string DeShuffle(this string shuffled, int key)
    {
        int size = shuffled.Length;
        char[] chars = shuffled.ToArray();
        var exchanges = GetShuffleExchanges(size, key);
        for (int i = 1; i < size; i++)
        {
            int n = exchanges[size - i - 1];
            char tmp = chars[i];
            chars[i] = chars[n];
            chars[n] = tmp;
        }
        return new string(chars);
    }
}

usage:

var originalString = "Hello world";
var shuffled = originalString.Shuffle(123);
var deShuffled = shuffled.DeShuffle(123);

// shuffled = "lelooH rwld";
// deShuffled = "Hello world";

The key must be an integer, if you need to use a string as password, just call GetHashCode() on it:

var shuffled = originalString.Shuffle(myStringKey.GetHashCode());

EDIT:

Now is exactly a Fisher–Yates shuffle algorithm implementation. Thanks to Jeff for the code

like image 182
digEmAll Avatar answered Sep 21 '22 01:09

digEmAll