Skip to content

Instantly share code, notes, and snippets.

@riyadparvez
Created July 2, 2013 18:29
Show Gist options
  • Select an option

  • Save riyadparvez/5911802 to your computer and use it in GitHub Desktop.

Select an option

Save riyadparvez/5911802 to your computer and use it in GitHub Desktop.
It selects k random element from n elements in C# using reservoir sampling algorithm. See http://propersubset.com/2010/04/choosing-random-elements.html
public static IList<T> ReservoirSampler<T>(IEnumerable<T> arr, int k)
{
if(arr == null)
{
throw new ArgumentNullException();
}
if( k <= 1 || k > arr.Count())
{
throw new ArgumentOutOfRangeException();
}
var list = arr.ToList();
var samples = new List<T>();
int n = 0;
var random = new Random();
foreach(var item in list)
{
n++;
if (samples.Count < k)
{
samples.Add(item);
}
else
{
var s = random.Next(n);
if(s < k)
{
samples[s] = item;
}
}
}
return samples;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment