Created
July 2, 2013 18:29
-
-
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
This file contains hidden or 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 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