Created
November 16, 2014 12:06
-
-
Save ArsalanDotMe/080d24a77816fefc54cd to your computer and use it in GitHub Desktop.
Shuffle Extension and Take random subelements
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 | |
{ | |
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source) | |
{ | |
return source.Shuffle(new Random()); | |
} | |
public static IEnumerable<T> Shuffle<T>( | |
this IEnumerable<T> source, Random rng) | |
{ | |
if (source == null) throw new ArgumentNullException("source"); | |
if (rng == null) throw new ArgumentNullException("rng"); | |
return source.ShuffleIterator(rng); | |
} | |
private static IEnumerable<T> ShuffleIterator<T>( | |
this IEnumerable<T> source, Random rng) | |
{ | |
var buffer = source.ToList(); | |
for (int i = 0; i < buffer.Count; i++) | |
{ | |
int j = rng.Next(i, buffer.Count); | |
yield return buffer[j]; | |
buffer[j] = buffer[i]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment