Skip to content

Instantly share code, notes, and snippets.

@koonuf
Last active February 16, 2016 18:18
Show Gist options
  • Save koonuf/0eefd5d3c2e8bc7eb6b4 to your computer and use it in GitHub Desktop.
Save koonuf/0eefd5d3c2e8bc7eb6b4 to your computer and use it in GitHub Desktop.
function extractRandomSubset (fullSet, subsetLength) {
var maxIndex, i, m, selectedItemIndex, selectedItem;
if(!fullSet.length){
return [];
}
maxIndex = fullSet.length - 1;
for (i = maxIndex, m = 0; i >= 0 && m < subsetLength; i--, m++) {
// find item between start of the set and
// ever decreasing index, which starts at the end of the set
selectedItemIndex = Math.round(Math.random() * i);
selectedItem = fullSet[selectedItemIndex];
// put found item to the end of the set
fullSet[selectedItemIndex] = fullSet[i];
fullSet[i] = selectedItem;
}
// extract (and remove) the end of the set,
// populated with found random items
return fullSet.splice(fullSet.length - m, m);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment