我很久以前写过这个。可能值得检查它是否适用于链接算法。众所周知,这类事情很容易出错。
//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;
}
}