65.9K
CodeProject is changing. Read more.
Home

Let's randomize IEnumerable

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Oct 12, 2011

CPOL
viewsIcon

9960

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;
}