Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Let's randomize IEnumerable

0.00/5 (No votes)
12 Oct 2011CPOL 10K  
Shuffle in O(N) time, vastly faster than the original version that calls RemoveAt().static Random r = new Random();public static IEnumerable Randomize(this IEnumerable source){ var list = source.ToList(); for (int i = 0; i < list.Count; i++) Swap(list, i,...
Shuffle in O(N) time, vastly faster than the original version that calls RemoveAt().
static Random r = new Random();
public static IEnumerable<T> Randomize<T>(this IEnumerable<T> source)
{
	var list = source.ToList();
	for (int i = 0; i < list.Count; i++)
		Swap(list, i, r.Next(list.Count));
	return list;
}
public static void Swap<T>(List<T> list, int i, int j)
{
	T tmp = list[i];
	list[i] = list[j];
	list[j] = tmp;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)