シャッフル!シャッフル!

C#のエクステンションメソッドを使ってシャッフル出来れば便利だと思って、Fisher-Yatesアルゴリズムで作ってみました。
IEnumerableを実装してるクラスなら、何でもシャッフルします。

Enjoy!

public static class ExtendedEnumerable
{
    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> collection)
    {
        // Fisher-Yates algorithm
        List<T> list = new List<T>(collection);
        Random r = new Random(DateTime.Now.Millisecond);
        int i = list.Count;

        while (i > 1)
        {
            int j = r.Next(i);
            i--;
            T temp = list[i];
            list[i] = list[j];
            list[j] = temp;
        }

        return list;
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<int> numberList = new List<int>();

        for (int i = 0; i < 10; i++)
        {
            numberList.Add(i);
        }

        foreach (var number in numberList.Shuffle<int>())
        {
            Console.WriteLine(number);
        }
}

参考:
Knuth, Donald E. (1969). The Art of Computer Programming volume 2: Seminumerical algorithms. Reading, MA: Addison-Wesley, 124–125.