1

到目前为止,我有以下随机播放代码,

    public static IList<T> Shuffle<T>(this IList<T> list)
    {
        var rnd = new Random();
        return list.OrderBy(element => rnd.Next());
    }

我像使用它一样,

    list = list.Shuffle();

我希望能够像使用它一样

    list.Shuffle(); // like list.Reverse();

所以基本上我想通过参考洗牌

我尝试了以下代码,

    public static void Shuffle<T>(this ref IList<T> list)
    {
        var rnd = new Random();
        list.OrderBy(element => rnd.Next());
    }

但它不起作用。

任何帮助是极大的赞赏!

4

1 回答 1

5

我很久以前写过这个。可能值得检查它是否适用于链接算法。众所周知,这类事情很容易出错。

    //Fisher-Yates_shuffle http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
    private static readonly ThreadLocal<Random> RandomThreadLocal =
        new ThreadLocal<Random>(() => new Random());
    public static void Shuffle<T>(this IList<T> list, int seed = -1)
    {
        var r = seed >= 0 ? new Random(seed) : RandomThreadLocal.Value;
        var len = list.Count;
        for (var i = len - 1; i >= 1; --i)
        {
            var j = r.Next(i);
            var tmp = list[i];
            list[i] = list[j];
            list[j] = tmp;
        }
    }

根据下面的评论,可以重载以获得更大的灵活性:

    private static readonly ThreadLocal<Random> RandomThreadLocal =
        new ThreadLocal<Random>(() => new Random());
    public static void Shuffle<T>(this IList<T> list, int seed)
    {
        list.Shuffle(new Random(seed));
    }

    public static void Shuffle<T>(this IList<T> list)
    {
        list.Shuffle(null);
    }

    public static void Shuffle<T>(this IList<T> list, Random rand)
    {
        var r = rand ?? RandomThreadLocal.Value;

        var len = list.Count;
        for (var i = len - 1; i >= 1; --i)
        {
            var j = r.Next(i);
            var tmp = list[i];
            list[i] = list[j];
            list[j] = tmp;
        }
    }
于 2012-11-06T17:10:01.550 回答