Last active
August 29, 2015 13:57
-
-
Save thynson/9658189 to your computer and use it in GitHub Desktop.
Get random k numbers from an iterator of arbitrary N length array where N is unknown. (pseudo code)
This file contains 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
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