Reputation:
I think I've come across an interesting question - how to scramble, then undo the scramble on an array. Please keep in mind this needs to be done using .Net 2.0.
My thought process is shown below:
byte[] b = new byte[] {1=>33,2=>19,3=>41,n=>N}
b.Sort();
The array might now look like this:
byte[] b = new byte[] {3=>41,2=>19,1=>33,n=>NN ... etc.};
Please, someone tell me what I'd like to do here is a possibility, and if it indeed is possible, please point me in the correct direction.
Thanks,
Evan
Upvotes: 3
Views: 357
Reputation: 41266
I would suggest shuffling and then unshuffling the array using the Fisher-Yates algorithm and a given integer key. The key can be fixed or random, but must be the same number for both operations in order to retrieve the original array.
Unscramble is a little bit more complicated than Scramble because the sequence of swaps must be generated using a Random initialised with the same seed, and then applied in reverse order.
void Scramble<T>(T[] array, int key)
{
var random = new Random(key);
for (int i = array.Length; i > 1; i--)
{
Swap(array, random.Next(i), i - 1);
}
}
void Unscramble<T>(T[] array, int key)
{
var random = new Random(key);
var swaps = new List<int>(array.Length);
for (int i = array.Length; i > 1; i--)
{
swaps.Add(random.Next(i));
}
swaps.Reverse();
for (int i = 0 ; i < swaps.Count; ++i)
{
Swap(array, swaps[i], i + 1);
}
}
void Swap<T>(T[] array, int i1, int i2)
{
T tmp = array[i2];
array[i2] = array[i1];
array[i1] = tmp;
}
Upvotes: 7