Last active
February 16, 2016 18:18
-
-
Save koonuf/0eefd5d3c2e8bc7eb6b4 to your computer and use it in GitHub Desktop.
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 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