Shuffle an Array in C#

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:

Shuffle Array

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.

Advertisements
This entry was posted in Programming and tagged , , , , , . Bookmark the permalink.

3 Responses to Shuffle an Array in C#

  1. Jack Evans says:

    I don’t understand how that is supposed to work. In the example you show the source list decreasing but that’s not what happens. It can pick from the entire source list on any loop and so you get repeated entries covering lost entries.

    For example your example would give CADBBA not CADBFE.

    • Me says:

      The array doesn’t actually shrink, but the last selected char is swapped with the last char in the array and the possible selection shrinks by 1 each time. So any selected item is moved to the end of the array where it can’t be selected again.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s