Peter Petrov’s Weblog

var me = from practice in programming where practice.IsBestPractice && practice.UseLambda select practice.OptimalPerformance;

Useful method – 2 of N – Shuffle/Randomize Array or List June 17, 2008

Filed under: C# — ppetrov @ 11:48 am
Tags:

From time to time I need to shuffle an array or a list. Unfortunately there is no such method as Randomize() or Shuffle() defined as a static method on the System.Array class or somewhere else. So I write down these extension methods on List<T> and T[].

For the array:

public static void ShuffleInPlace<T>(this T[] values)
{
    ExtensionUtils.GenericShuffle(values);
}

public static T[] Shuffle<T>(this T[] values)
{
    if (values == null)
    {
        throw new ArgumentNullException("values");
    }
    T[] copy = new T[values.Length];
    Array.Copy(values, copy, values.Length);

    copy.ShuffleInPlace();

    return copy;
}

For the list:


public static List<T> Shuffle<T>(this List<T> values)
{
 List<T> copy = new List<T>(values);
 copy.ShuffleInPlace();
 return copy;
}

public static void ShuffleInPlace<T>(this List<T> values)
{
 ExtensionUtils.GenericShuffle(values);
}

where the class ExtensionUtils is defined like this

public static class ExtensionUtils
{
    public static void GenericShuffle<T>(IList<T> values)
    {
        if (values == null)
        {
            throw new ArgumentNullException("values");
        }
        if (values.Count > 0)
        {
            Random r = new Random();

            int position = 0;
            for (int i = values.Count - 1; i > 0; i--)
            {
                position = r.Next(i + 1);
                T temp = values[i];
                values[i] = values[position];
                values[position] = temp;
            }
        }
    }
} 

Now we can shuffle out arrays or lists very easily.

Advertisements
 

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