Skip to content

Instantly share code, notes, and snippets.

@thynson
Last active Aug 29, 2015
Embed
What would you like to do?
Get random k numbers from an iterator of arbitrary N length array where N is unknown. (pseudo code)
function(iter, k) {
var array = [];
var count = 0;
for (var val = iter(); val !== undefined; val = iter()) {
count ++;
if (array.length < k)
array.push_back(val);
else {
var luck = rand() % count;
if (luck < k) {
array.unqueue_at(luck);
array.push_back(val);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment