Skip to content

Instantly share code, notes, and snippets.

@ArsalanDotMe
Created November 16, 2014 12:06
Show Gist options
  • Save ArsalanDotMe/080d24a77816fefc54cd to your computer and use it in GitHub Desktop.
Save ArsalanDotMe/080d24a77816fefc54cd to your computer and use it in GitHub Desktop.
Shuffle Extension and Take random subelements
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