The Fisher-Yates-Durstenfeld shuffle is a proven technique that's easy to implement. Here's an extension method that will perform an in-place shuffle on any IList<T>
.
(It should be easy enough to adapt if you decide that you want to leave the original list intact and return a new, shuffled list instead, or to act on IEnumerable<T>
sequences, à la LINQ.)
var list = new List<string> { "the", "quick", "brown", "fox" };
list.ShuffleInPlace();
// ...
public static class ListExtensions
{
public static void ShuffleInPlace<T>(this IList<T> source)
{
source.ShuffleInPlace(new Random());
}
public static void ShuffleInPlace<T>(this IList<T> source, Random rng)
{
if (source == null) throw new ArgumentNullException("source");
if (rng == null) throw new ArgumentNullException("rng");
for (int i = 0; i < source.Count - 1; i++)
{
int j = rng.Next(i, source.Count);
T temp = source[j];
source[j] = source[i];
source[i] = temp;
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…