Last active
December 10, 2015 09:28
-
-
Save spetroll/4414158 to your computer and use it in GitHub Desktop.
Shuffle Enumeration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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