Created
September 22, 2016 12:54
-
-
Save DimitryDushkin/5a893ce26a37aafaacc7cc58f0b62e51 to your computer and use it in GitHub Desktop.
Get random array elements from array with limit
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 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