I needed to randomize an enumerable collection. Here's what I came up with in the 60 seconds I thought it deserved.
Your challenge:
- Do it better. better = faster with same number of items and/or faster with
n
items.
- Prove it.
using System;
using System.Collections.Generic;
static class IEnumerableExtension
{
public static IEnumerable<T> Randomize<T>(this IEnumerable<T> collection)
{
var list = new List<T>(collection);
var randomizer = new Random();
for (int i = list.Count; i > 0; i--)
{
int r = randomizer.Next(0, i);
yield return list[r];
list.RemoveAt(r);
}
}
}