Skip to content

Instantly share code, notes, and snippets.

@myui
Last active January 2, 2016 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myui/8314063 to your computer and use it in GitHub Desktop.
Save myui/8314063 to your computer and use it in GitHub Desktop.
reservoir sampling
T add(T item) {
T old = null;
if(position < numSamples) {// reservoir not yet full, just append
samples[position] = item;
} else {// find a item to replace
int replaceIndex = rand.nextInt(position + 1);
if(replaceIndex < numSamples) {// replacement opportunity decreases over a time
old = samples[replaceIndex];
samples[replaceIndex] = item;
}
}
position++;
return old;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment