Jump to content


Check out our Community Blogs





- - - - -

Shuffle an Array in C#

  Posted by Barnsite, 15 January 2013 · 2660 views

As part of a basic guessing game I wanted to be able to shuffle an array of n chars into a random order.
The method I decided to use was the following.
Create a loop to iterate n times (where n is the number of elements in the array). Randomly select one array element and add this to a new array. Replace the removed item with the last item in the array (effectively making the array one element smaller). This seemed easier than shifting all the elements along one to remove the gap (which was my first thought). The new array will hold the ‘shuffled’ items.
Pictorial example:
Posted Image
Shuffle Array
Here you can see each step (the selected item is shown in Red).
In code this translates to the following shuffle function:

private char[] shuffle(char[] charArray)
{
char[] shuffledArray = new char[charArray.Length];
int rndNo;

Random rnd = new Random();
for (int i = charArray.Length; i >= 1; i--)
{
rndNo = rnd.Next(1, i+1) - 1;
shuffledArray[i - 1] = charArray[rndNo];
charArray[rndNo] = charArray[i - 1];
}
return shuffledArray;
}

This can be called in the following way:

char[] list1 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M' };
char[] shuffled = shuffle((char[])list1.Clone());

Here the list1 array will be shuffled and returned to the shuffled array. Note that I pass a clone of the list1 array, this is because arrays are passed by reference and if I didn’t do this the list1 array would be altered which I didn’t want.
One other thing to note is that this would work for any kind of array, just by changing the array type.
I don’t know exactly how random this function is. However, I ran a loop shuffling 13 chars 1,000,000 times and had 42 duplicate outputs.
http://feeds.wordpre...dpress.com/542/ Posted Image

Source

  • 0