Skip to content

Instantly share code, notes, and snippets.

@DimitryDushkin
Created September 22, 2016 12:54
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 DimitryDushkin/5a893ce26a37aafaacc7cc58f0b62e51 to your computer and use it in GitHub Desktop.
Save DimitryDushkin/5a893ce26a37aafaacc7cc58f0b62e51 to your computer and use it in GitHub Desktop.
Get random array elements from array with limit
function getRandomArrayElements(arr, count) {
var sliceStart = getRandomInt(0, arr.length - count),
randomSlice = arr.slice(sliceStart, sliceStart + count);
return shuffleArray(randomSlice);
}
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function shuffleArray(array) {
var counter = array.length;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
var index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
var temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment