05 December 2008

Randomly Rotate Array Elements

Array shuffling can be at times quiet confusing especially if you want to do it randomly. But hears a simple code function in C# which uses the Array.Reverse function that will save the day :

protected void myFunction()
{
Array test = new Array('abc','asd','yyj','jsd','jrd','tyf','qwe','asd');
Random random = new Random();
int index1=random.Next(0, test.Length);

}

protected Array RotateArrayFromLeft(Array ArrayToBeRotated, int N)
{
int a_length = ArrayToBeRotated.Length;
if ((N >= 0) && (N <= a_length))
{
Array.Reverse(ArrayToBeRotated, 0, N);
Array.Reverse(ArrayToBeRotated, N, alength - N);
Array.Reverse(ArrayToBeRotated);
}
return ArrayToBeRotated;
}
Note: This function shuffles a array from its left position, you can modify it according to your
needs.

No comments: