到目前为止,我有以下Shuffle代码,
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());
}
但它不起作用。
非常感谢任何帮助!
答案 0 :(得分: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;
}
}