Skip to content

Instantly share code, notes, and snippets.

@spetroll
Last active December 10, 2015 09:28
Show Gist options
  • Save spetroll/4414158 to your computer and use it in GitHub Desktop.
Save spetroll/4414158 to your computer and use it in GitHub Desktop.
Shuffle Enumeration
public static class EnumerableExtensions
{
private static readonly Random rng = new Random();
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
{
if (source == null)
throw new ArgumentNullException("source");
if (rng == null)
throw new ArgumentNullException("rng");
return source.ShuffleIterator();
}
private static IEnumerable<T> ShuffleIterator<T>(this IEnumerable<T> source)
{
T[] elements = source.ToArray();
// Note i > 0 to avoid final pointless iteration
for (int i = elements.Length - 1; i > 0; i--)
{
// Swap element "i" with a random earlier element it (or itself)
int swapIndex = rng.Next(i + 1);
yield return elements[swapIndex];
elements[swapIndex] = elements[i];
}
// there is one item remaining that was not returned - we return it now
yield return elements[0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment